Creating a WebMvc component test
Another one of the collection of *Test
slices is @WebMvcTest
, which allows us to create tests for the WebMvc part of the application, quickly testing controllers, filters, and so on, while providing ability to use @MockBean
to configure the necessary dependencies such as services, data repositories, and so on.
This is another very useful testing slice provided by the Spring Boot Test Framework, and we will explore its use in this recipe, taking a look at how we can create an Mvc layer test for our BookController
file, mocking the BookRepository
service with a predefined dataset and making sure the returned JSON document is what we would expect based on that data.
How to do it...
- First, we will create a new
WebMvcBookControllerTests
test class in thesrc/test/java/com/example/bookpub
directory at the root of our project with the following content:
import static org.hamcrest.Matchers.containsString; import static org.mockito.BDDMockito.given; import static org...