通常只限于单个控制器(controller)使用,并结合@MockBean以提供需要的协作者(collaborators)的mock实现。也会自动配置MockMvc,Mock MVC为快速测试MVC控制器提供了一种强大的方式,并且不需要启动一个完整的HTTP服务器。

    如果需要定义自定配置(auto-configuration)的元素(比如什么时候使用servlet filters),你可以使用的属性。

    1. import com.gargoylesoftware.htmlunit.*;
    2. import org.junit.*;
    3. import org.junit.runner.*;
    4. import org.springframework.beans.factory.annotation.*;
    5. import org.springframework.boot.test.autoconfigure.web.servlet.*;
    6. import org.springframework.boot.test.mock.mockito.*;
    7. import static org.assertj.core.api.Assertions.*;
    8. import static org.mockito.BDDMockito.*;
    9. @RunWith(SpringRunner.class)
    10. @WebMvcTest(UserVehicleController.class)
    11. public class MyHtmlUnitTests {
    12. @Autowired
    13. private WebClient webClient;
    14. @MockBean
    15. private UserVehicleService userVehicleService;
    16. @Test
    17. public void testExample() throws Exception {
    18. given(this.userVehicleService.getVehicleDetails("sboot"))
    19. .willReturn(new VehicleDetails("Honda", "Civic"));
    20. HtmlPage page = this.webClient.getPage("/sboot/vehicle.html");
    21. assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic");
    22. }
    23. }

    附录中可以查看开启的自动配置列表。