MVC Test framework
Provide support for Spring MVC code, having requests processed through DispatcherServlet without container.
![](https://blog.kitboga.net/wp-content/uploads/2023/11/image-25.png)
![](https://blog.kitboga.net/wp-content/uploads/2023/11/image-26.png)
![](https://blog.kitboga.net/wp-content/uploads/2023/11/image-27.png)
It uses MockMvcRequestBuilders and MockMvcResultMatchers.
Web environment types: DEFINED_PORT, MOCK, NONE, RANDOM_PORT.
Default is Mock
@LocalServerPort or @Value("${local.server.port}") to get test local port.
TestRestTemplate
Alternative to RestTemplate for integration tests.
- takes a relative path, instead of an absolute one.
- fault tolerant, does not throw exception when error is received
- ignores cookies and redirects
- can be customized with RestTemplateBuilder
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class AccountClientBootTest{
@Autowired
private TestRestTemplate restTemplate;
//Test code
}
![](https://springboot.kitboga.net/wp-content/uploads/2024/06/image-29.png)
Slice testing
Performs isolated testing within a slice of an application, where dependencies need to be mocked.
Uses @WebMvcTest annotation and @MockBean.
@WebMvcTest(AccountController.class)
public class AccountControllerBootTests{
@Autowired
private MockMvc mockMvc;
@MockBean
private AccountManager accountManager;
@Test
public void someTest() throws Exception {
// code
}
}
![](https://blog.kitboga.net/wp-content/uploads/2023/11/image-29.png)
Annotations
- @Mock – from Mockito framework, used when Spring context is not required.
- @MoockBean – from Spring boot, used with Spring context
- @SpringJUnitWebConfig – used to configure test class with a context
- @DataJpaTest – configures TestEntityManager an can use @AutoConfigureTestDatabase
![](https://blog.kitboga.net/wp-content/uploads/2023/11/image-30.png)
References