测试用例如下:
package com.jack.apple.user.controller;
import com.jack.apple.user.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.jupiter.api.Assertions.*;
@Slf4j
@SpringBootTest
@ActiveProfiles(value = {"test"})
public class AppleUserControllerTest {
protected MockMvc mockMvc;
@BeforeEach
void setUp() {
//
mockMvc = MockMvcBuilders
.webAppContextSetup((WebApplicationContext) SpringUtils.getContext())
.build();
}
@Test
void mockRestfulGetUserByIdTest() throws Exception {
MockHttpServletRequestBuilder mockRequestBuilder = MockMvcRequestBuilders
.get("/users/getUserInfo/1")
.accept(MediaType.APPLICATION_JSON);
// 发送请求
ResultActions resultActions = mockMvc.perform(mockRequestBuilder);
// 请求状态
resultActions.andExpect(MockMvcResultMatchers.status().isOk());
// 请求结果
MvcResult mvcResult = resultActions.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String responseContent = response.getContentAsString();
log.info("response info: {}", responseContent);
assertTrue(StringUtils.isNotEmpty(responseContent));
}
}
测试依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
maven构建明显如下:
mvn clean package -e
构建输出信息如下:
从输出信息可以看到测试用例数为零.
查看一下maven-surefire-plugin插件的使用介绍。官网地址:
https://maven.apache.org/surefire/maven-surefire-plugin/examples/junit-platform.html
显示引用该插件依赖后可正常执行单元测试
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
</plugins>