Unit tests for web layers involve testing the Controllers--REST and otherwise.
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 as follows:
@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.