spring web 测试有三种方式
1. 自己初始化 MockMvc
2.依赖@springbootTest 它会帮你生产 webTestClient ,只需自己注入即可。
3.启动的时候,不加载整个应用,进行远程调用 使用WebClient
spring web 最常用导入静态方法
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
junit 5断言。
import static org.junit.jupiter.api.Assertions.*;
一、启用测试用例
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { WebMvcConfiguration.class, DataConfiguration.class }) @WebAppConfiguration
二、初始化mvc
private MockMvc mockMvc; @Autowired private WebApplicationContext wac; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); }
三、常用方法
this.mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML)).andDo(print());
@Test public void testForm() throws Exception{ this.mockMvc.perform(post("/").param("text", "text").param("summary", "summary")) .andExpect(status().is3xxRedirection()).andDo(print()); } /** * 对于 @Valid 无效,后续解决了进行补充 * @throws Exception */ @Test public void testFormFail() throws Exception{ this.mockMvc.perform(post("/").param("text", "text").param("summary","")) .andDo(print()); }
如果使用 @SpringBootTest 则可以使用
@Autowired
private WebTestClient webTestClient;
@Test
public void test1CreateGithubRepository() {
RepoRequest repoRequest = new RepoRequest("test-webclient-repository", "Repository created for testing WebClient");
webTestClient.post().uri("/api/repos")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8)
.body(Mono.just(repoRequest), RepoRequest.class)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
.expectBody()
.jsonPath("$.name").isNotEmpty()
.jsonPath("$.name").isEqualTo("test-webclient-repository");
}
使用 webClient
WebClient webClient = WebClient.builder() .baseUrl("https://api.github.com") .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/vnd.github.v3+json") .defaultHeader(HttpHeaders.USER_AGENT, "Spring 5 WebClient") .build(); public Flux<GithubRepo> listGithubRepositories(String username, String token) { return webClient.get() .uri("/user/repos") .header("Authorization", "Basic " + Base64Utils .encodeToString((username + ":" + token).getBytes(UTF_8))) .exchange() .flatMapMany(clientResponse -> clientResponse.bodyToFlux(GithubRepo.class)); }