多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 40.3.7 自动配置的Spring MVC测试 你可以使用`@WebMvcTest`检测Spring MVC控制器是否工作正常,该注解将自动配置Spring MVC设施,并且只扫描注解`@Controller`,`@ControllerAdvice`,`@JsonComponent`,`Filter`,`WebMvcConfigurer`和`HandlerMethodArgumentResolver`的beans,其他常规的`@Component` beans将不会被扫描。 通常`@WebMvcTest`只限于单个控制器(controller)使用,并结合`@MockBean`以提供需要的协作者(collaborators)的mock实现。`@WebMvcTest`也会自动配置`MockMvc`,Mock MVC为快速测试MVC控制器提供了一种强大的方式,并且不需要启动一个完整的HTTP服务器。 **注** 使用`@AutoConfigureMockMvc`注解一个non-`@WebMvcTest`的类(比如`SpringBootTest`)也可以自动配置`MockMvc`。 ```java import org.junit.*; import org.junit.runner.*; import org.springframework.beans.factory.annotation.*; import org.springframework.boot.test.autoconfigure.web.servlet.*; import org.springframework.boot.test.mock.mockito.*; import static org.assertj.core.api.Assertions.*; import static org.mockito.BDDMockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @WebMvcTest(UserVehicleController.class) public class MyControllerTests { @Autowired private MockMvc mvc; @MockBean private UserVehicleService userVehicleService; @Test public void testExample() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")) .willReturn(new VehicleDetails("Honda", "Civic")); this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); } } ``` **注** 如果需要定义自定配置(auto-configuration)的元素(比如什么时候使用servlet filters),你可以使用`@AutoConfigureMockMvc`的属性。 如果你使用HtmlUnit或Selenium, 自动配置将提供一个`WebClient` bean和/或`WebDriver` bean,以下是使用HtmlUnit的示例: ```java import com.gargoylesoftware.htmlunit.*; import org.junit.*; import org.junit.runner.*; import org.springframework.beans.factory.annotation.*; import org.springframework.boot.test.autoconfigure.web.servlet.*; import org.springframework.boot.test.mock.mockito.*; import static org.assertj.core.api.Assertions.*; import static org.mockito.BDDMockito.*; @RunWith(SpringRunner.class) @WebMvcTest(UserVehicleController.class) public class MyHtmlUnitTests { @Autowired private WebClient webClient; @MockBean private UserVehicleService userVehicleService; @Test public void testExample() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")) .willReturn(new VehicleDetails("Honda", "Civic")); HtmlPage page = this.webClient.getPage("/sboot/vehicle.html"); assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic"); } } ``` 在[附录](http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#test-auto-configuration)中可以查看`@WebMvcTest`开启的自动配置列表。