Testing web controllers with MockMVC
With web pages being a key component of a web app, Spring comes loaded with tools to easily verify web functionality.
While we could instantiate a Spring MVC web controller and interrogate it using various assertions, this would get clunky. And part of what we seek is going through the machinery of Spring MVC. Essentially, we need to make a web call and wait for a controller to respond.
To test the HomeController
class we built earlier in this book, we need to create a new test class, HomeControllerTest.java
, underneath src/test/java
in the same package as HomeController
:
@WebMvcTest(controllers = HomeController.class) public class HomeControllerTest { @Autowired MockMvc mvc; @MockBean VideoService videoService; @Test @WithMockUser void indexPageHasSeveralHtmlForms() throws Exception { String html = mvc.perform( // get...