一般SpringBoot Mvc 测试,需要配合@SpringBootTest来一起使用。需要注意的是,SpringBootTest注解默认提供一个mock web env(一个轻量级web server),这个mock server 有些限制,比如servlet container 底层行为、自定义error page等行为是不支持的。官方说明如下:
提供MockMvc、WebTestClient两种方式来模拟调用http请求
| 注解 | 说明 |
|---|---|
| MockMvc | 只支持serlvet 容器mvc |
| WebTestClient | 只支持webFlux,当classpath 有spring webflux jar时,会自动实例化WebTestClient |
注解属性说明
| 属性 | 说明 |
|---|---|
| addFilters | 是否添加filter 到web 容器中,默认为true |
| 打印MvcResult模式是哪种,默认为MockMvcPrint.SYSTEM_OUT |
关键实现class 见SpringBootMockMvcBuilderCustomizer
注解源码@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@documented
@Inherited
@importAutoConfiguration
@PropertyMapping("spring.test.mockmvc")
public @interface AutoConfigureMockMvc {
boolean addFilters() default true;
@PropertyMapping(skip = SkipPropertyMapping.ON_DEFAULT_VALUE)
MockMvcPrint print() default MockMvcPrint.DEFAULT;
boolean printOnlyOnFailure() default true;
@PropertyMapping("webclient.enabled")
boolean webClientEnabled() default true;
@PropertyMapping("webdriver.enabled")
boolean webDriverEnabled() default true;
}
AutoConfigureWebTestClient注解
只提供WebTestClient方式来模拟调用http请求
注解属性说明
| 属性 | 说明 |
|---|---|
| timeout | 超时时间 |
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@documented
@Inherited
@importAutoConfiguration
@PropertyMapping("spring.test.webtestclient")
public @interface AutoConfigureWebTestClient {
String timeout() default "";
}
demo 代码
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false, printonlyOnFailure = true)
public class SpringBootMvcDemoTest {
@Test
void mvcMockTest(@Autowired MockMvc mvc) throws Exception {
mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("hello world"));
}
@Test
void webClientTest(@Autowired WebTestClient client) throws Exception {
client.get().uri("/").exchange().expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello World");
}
}



