标签搜索

目 录CONTENT

文章目录

SpringBoot的Junit测试用例

陈铭
2023-05-27 / 0 评论 / 0 点赞 / 86 阅读 / 744 字 / 正在检测是否收录...

pom

        <!--springMVC-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- lombok依赖包 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
            <scope>provided</scope>
        </dependency>

        <!--测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

工具类

package ltd.cmjava.controller.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.nio.charset.StandardCharsets;

/**
 *
 **/
@RequiredArgsConstructor
@Component
public class MockUtil {

    private final ObjectMapper objectMapper;

    private final WebApplicationContext webApplicationContext;

    public String post(String url,Object body) throws Exception {
        MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        return mockMvc.perform(
                        MockMvcRequestBuilders.post(url)
                                .contentType(MediaType.APPLICATION_JSON)
                                .content(objectMapper.writeValueAsString(body))
                                .accept(MediaType.APPLICATION_JSON))
                .andReturn()
                .getResponse().getContentAsString(StandardCharsets.UTF_8);
    }

    public String get(String url) throws Exception {
        MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        return mockMvc.perform(
                        MockMvcRequestBuilders.get(url)
                                .accept(MediaType.APPLICATION_JSON))
                .andReturn()
                .getResponse().getContentAsString(StandardCharsets.UTF_8);
    }
}

测试类

package ltd.cmjava.controller.admin;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import ltd.cmjava.WebApplication;
import ltd.cmjava.controller.util.MockUtil;
import ltd.cmjava.entity.User;
import ltd.cmjava.service.AdminService;
import ltd.cmjava.utils.encrypt.RsaUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.context.WebApplicationContext;

@SuppressWarnings("all")
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AdminControllerTest {

    private static User successUser;
    private static User failureUser;
    @Autowired
    private AdminController adminController;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private AdminService adminService;
    @Autowired
    private WebApplicationContext webApplicationContext;
    @Autowired
    private RsaUtil rsaUtil;
    @Autowired
    private MockUtil mockUtil;

    @Before
    public void user() {
        successUser = new User(1, "xx", "xx");
        successUser.setUsername(rsaUtil.publicEncrypt(successUser.getUsername()));
        successUser.setPassword(rsaUtil.publicEncrypt(successUser.getPassword()));

        failureUser = new User(1, "xx", "xx");
        failureUser.setUsername(rsaUtil.publicEncrypt(failureUser.getUsername()));
        failureUser.setPassword(rsaUtil.publicEncrypt(failureUser.getPassword()));
    }

    @Test
    public void login() throws Exception {
        String result = mockUtil.post("/adminLogin", successUser);
        log.info(result);
    }

    @Test
    public void loginOut() throws Exception {
        String result = mockUtil.get("/adminOut");
        log.info(result);
    }
}

或者这么写

package ltd.cmjava;

import lombok.extern.slf4j.Slf4j;
import ltd.cmjava.util.MockUtil;
import org.junit.Assert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import java.nio.charset.StandardCharsets;

@SuppressWarnings("all")
@Slf4j
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {

    @Autowired
    private MockUtil mockUtil;

    @Autowired
    private MockMvc mockMvc;

    @RepeatedTest(2)
    @org.junit.Test
    public void getVisitorNum() throws Exception {
        String result = mockUtil.get("/getVisitorNum");
        String result0 = get("/getVisitorNum");
        log.info(result);
        log.info(result0);
    }

    @RepeatedTest(3)
    @org.junit.Test
    public void repeat() throws Exception {
        System.out.println(1);
        Assert.assertNull(null);
    }
    
    @ParameterizedTest
    @ValueSource(ints = {1, 2, 3})
    @DisplayName("参数化测试")
    void paramTest(int a) {
        Assert.assertTrue(a > 0 && a < 4);
        Assertions.assertTrue(a > 0 && a < 4);
    }

    public String get(String url) throws Exception {
        return mockMvc.perform(
                        MockMvcRequestBuilders.get(url)
                                .accept(MediaType.APPLICATION_JSON))
                .andReturn()
                .getResponse().getContentAsString(StandardCharsets.UTF_8);
    }
}
0

评论区