Unit tests for web layers involve testing the controllers—REST and otherwise—so we recommend the following:
- Using Mock MVC for web layers built on Spring MVC.
- Jersey Test Framework is a good choice for REST services built using Jersey and JAX-RS.
A quick example of setting up the Mock MVC framework is shown in the following example:
@RunWith(SpringRunner.class)
@WebMvcTest(TodoController.class)
public class TodoControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private TodoService service;
//Tests
}
Using @WebMvcTest will allow us to use autowire MockMvc and execute web requests. A great feature of @WebMVCTest is that it only instantiates the controller components. All other Spring components are expected to be mocked and can be autowired using @MockBean.