单元测试实践
maven包说明
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
具体使用
@SpringBootTest(classes = ChatSetApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("dev")
class CusFastMenuConfigControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
private HttpHeaders headers;
public static final String baseUrl = "/v6/menuConfig";
private final Logger logger = LogManager.getLogger(CusFastMenuConfigControllerTest.class);
ObjectMapper objectMapper = new ObjectMapper();
@BeforeEach
public void init(){
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
MultiValueMap<String, String> headerMap = new LinkedMultiValueMap<>();
headerMap.add("language", "zh");
headerMap.add("temp-id", "123456");
headers = new HttpHeaders();
headers.addAll(headerMap);
}
@Test
void findCusMenuConfigByKeyword() throws Exception {
CusMenuConfigFindReqVo cusMenuConfigFindReqVo = new CusMenuConfigFindReqVo();
cusMenuConfigFindReqVo.setMenuType("");
cusMenuConfigFindReqVo.setMenuName("");
cusMenuConfigFindReqVo.setCompanyId("");
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(baseUrl + "/findCusMenuConfigByKeyword")
.headers(headers)
.content(objectMapper.writeValueAsString(cusMenuConfigFindReqVo))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.jsonPath("$.retMsg").value("成功"))
.andReturn();
String contentAsString = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
logger.info(contentAsString);
}
}
参数化测试
- 需要自定义一个参数提供器继承ArgumentsProvider接口
static class CustomObjectProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(org.junit.jupiter.api.extension.ExtensionContext context) {
return Stream.of(
Arguments.of(new CusMenuConfigFindReqVo()),
Arguments.of(new CusMenuConfigFindReqVo())
);
}
}
@ParameterizedTest
@ArgumentsSource(CustomObjectProvider.class)
void findCusMenuConfigByKeyword(CusMenuConfigFindReqVo cusMenuConfigFindReqVo) throws Exception {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(baseUrl + "/findCusMenuConfigByKeyword")
.headers(headers)
.content(objectMapper.writeValueAsString(cusMenuConfigFindReqVo))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.jsonPath("$.retMsg").value("成功"))
.andReturn();
String contentAsString = mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8);
logger.info(contentAsString);
}
问题思考:
- 测试某一个controller的接口时出现了多个controller的结果,为什么某一个controller的class会有两个?
- 问题找到了因为将测试类和controller类都放到了同一个包下,@Slf4j都给覆盖了,这是因为
@Slf4j
是Lombok库提供的注解,在编译时会生成一个名为log
的日志对象。 - 解决方案:在Code Coverage中添加需要扫描的包