@WebMvcTest注解簡介
Spring框架提供了@WebMvcTest這一注解來配置Controller的上下文環境,以幫助實現對Controller層的測試。從中可以看出,
- 只實例化Controller。默認實例化所有的Controller,也可以指定只實例化某一到多個Controller。
- 會實例化一個MockMvc的bean,用于模擬收發http請求和響應。
- 默認搜索@SpringBootConfiguration注解的類作為配置類。(這里坑最多)
- 通過properties 指定運行時的參數
具體可以參見 spring.factories
以下是這個注解的定義,
package org.springframework.boot.test.autoconfigure.web.servlet;
//import
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(WebMvcTestContextBootstrapper.class)
@ExtendWith({SpringExtension.class})
@OverrideAutoConfiguration(
enabled = false
)
@TypeExcludeFilters({WebMvcTypeExcludeFilter.class})
@AutoConfigureCache
@AutoConfigureWebMvc
@AutoConfigureMockMvc
@ImportAutoConfiguration
public @interface WebMvcTest {
String[] properties() default {};
@AliasFor("controllers")
Class<?>[] value() default {};
@AliasFor("value")
Class<?>[] controllers() default {};
boolean useDefaultFilters() default true;
Filter[] includeFilters() default {};
Filter[] excludeFilters() default {};
@AliasFor(
annotation = ImportAutoConfiguration.class,
attribute = "exclude"
)
Class<?>[] excludeAutoConfiguration() default {};
}
接下來看一下,如何通過@WebMvcTest搭配MockMvc和@MockBean來進行單個Controller的測試
案例1-單個Controller的測試
package com.testlink4j.controller;
//import
@WebMvcTest(KeywordsRestController.class)
public class KeywordsControllerMockBean2Test {
@MockBean
private KeywordsService keywordsServic;
@Autowired
private MockMvc mockMvc;
@Test
public void CreateKeywordsSuccessfullyTest() throws Exception {
Keywords keywords=Keywords.builder().id(666).keyword("tester").testproject_id(333).notes("tester").build();
Mockito.when(keywordsServic.findKeywordById(1)).thenReturn(keywords);
String responseString = mockMvc.perform(
get("/api/keywords?id=1") //請求的url,請求的方法是Post
.contentType(MediaType.APPLICATION_JSON) //數據的格式
// .content(jsonString) //body
).andExpect(status().isOk()) //返回的狀態是200
.andDo(print()) //打印出請求和相應的內容
.andReturn().getResponse().getContentAsString(); //將相應的數據轉換為字符串
assertThatJson(responseString).isEqualTo(keywords);
assertThatJson(responseString).isEqualTo(keywords);
}
}
以上代碼實現了
1在Sping容器中只注入指定的KeywordsRestController,
2并通過@MockBean將該Controller對Service的依賴進行了mock 。在測試時,
3通過MockMvc模擬發送HTTP GET請求,并對http響應的狀態碼進行了驗證,
4對返回的結果也進行了驗證。
案例2-請求格式校驗
再編寫一個針對入參的校驗用例
(@RequestParam(value = "id", required = true)
也就是說,id這個字段是必填項
@Test
public void CreateKeywordsNoIdProvidedTest() throws UnsupportedEncodingException, Exception {
mockMvc.perform(
get("/api/keywords?idd=1") //請求的url,請求的方法是Get
.contentType(MediaType.APPLICATION_JSON) //數據的格式
// .content(jsonString) //body
).andExpect(status().is(400)) //返回的狀態是400
.andDo(print()); //打印出請求和相應的內容
}
}
以上用例假設因為筆誤,id錯寫成了idd,用例預期HTTP狀態碼會從200變成400 Bad Request ,即客戶端錯誤。
以下是Spring1.4引入的各層進行單測的注解
@WebMvcTest - for testing the controller layer
@JsonTest - for testing the JSON marshalling and unmarshalling
@DataJpaTest - for testing the repository layer
@RestClientTests - for testing REST clients
本次主要介紹了@WebMvcTest,后續我們會繼續涵蓋其它注解。
By 軟-件-測試-那-些 事