美文网首页
SpringBoot-单元测试

SpringBoot-单元测试

作者: 张明学 | 来源:发表于2020-04-14 21:17 被阅读0次

本文主要介绍如何对SpringBoot进行Service和Controller进行单元测试


  • Jar依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Service层单元测试


测试环境:

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class BaseSpringBootTest {

    @Before
    public void init() {
        log.info("开始测试");
    }

    @After
    public void after() {
        log.info("结束测试");
    }
}

@RunWith 该注解为SpringApplication创建上下文并支持Spring Boot特性。
@SpringBootTest 该注解会搜索@SpringBootApplication注解的类(即SpringBoot的启动类),它是按照当前单元测试类(包括BaseSpringBootTest的子类)的package往父层级逐级搜索。如果搜索则报错:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

请注意以下两点

  1. @SpringBootTest(classes = WebApplication.class) // WebApplication即为配置了@SpringBootApplication注解的类
  2. 将所有测试用例类的测试包名都放到@SpringBootApplication所在类的package下面

Controller层单元测试


Controller层单元测试有两种方式:mock方式和容器的方式启动方式

1. mock方式对 Controller进行单元测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApplication.class)
// 配置mock
@AutoConfigureMockMvc
@Slf4j
public class BaseMockSpringBootTest {

    @Autowired
    protected MockMvc mvc;

    protected MockHttpSession mockHttpSession;
    protected MockHttpServletRequestBuilder mockHttpServletRequestBuilder;

    @Before
    public void init() {
        log.info("-->开始测试<--");
        mockHttpSession = new MockHttpSession();
        mockHttpSession.setAttribute("testSession", "value");
    }

    @Test
    public void getSampleTest() throws Exception {
        mockHttpServletRequestBuilder = MockMvcRequestBuilders.get("/sample/test")
                .header("header1", "v1")
                .session(mockHttpSession);

        MvcResult mvcResult = mvc.perform(mockHttpServletRequestBuilder)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
        log.info(mvcResult.getResponse().getContentAsString());
    }

    @After
    public void after() {
        log.info("-->测试结束<--");
    }

}

@SpringBootTest的注意方式和对Service层的单元测试一样。这里主要添加@AutoConfigureMockMvc,当然这里也可以对Service层进行单元测试。
参数传入:

  • Post方法,contentType为application/json
mockHttpServletRequestBuilder = MockMvcRequestBuilders.post(basePath + "/sample/test")
                .contentType(MediaType.APPLICATION_JSON)
                .content(JSON.toJSONString(userVo));
  • Post方法,表单提交或Get请求
mockHttpServletRequestBuilder = MockMvcRequestBuilders.post(basePath + "/sample/test")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("param1","value1");
mockHttpServletRequestBuilder = MockMvcRequestBuilders.get(basePath + "/sample/test")
                .param("param1","value1");
2. 容器的方式启动方式 Controller进行单元测试

容器的方式启动方式主要使用@SpringBootTest配置。
Jar依赖:

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-webflux</artifactId>
       <scope>test</scope>
</dependency>
@RunWith(SpringRunner.class)
// 配置本地随机端口,服务器会选择一个空闲的端口使用,避免端口冲突
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
public class BaseWebfluxSpringBootTest {

    @Autowired
    private WebTestClient webClient;

    @Test
    public void exampleTest() throws Exception {
        byte[] result = this.webClient.get().uri("/sample/test").exchange()
                .expectStatus().isOk()
                .expectBody().returnResult().getResponseBody();

        log.info(new String(result, "utf-8"));
    }

}

相关文章

网友评论

      本文标题:SpringBoot-单元测试

      本文链接:https://www.haomeiwen.com/subject/sbmxvhtx.html