Skip to content

Spring Framework Blog

Menu
  • Home
  • Spring
  • Spring Boot
  • About
Menu

Spring MVC Tests

Posted on May 29, 2024June 14, 2024 by Armando Marques

Table of Contents

Toggle
  • MVC Test framework
  • TestRestTemplate
  • Slice testing
  • Annotations

MVC Test framework

Provide support for Spring MVC code, having requests processed through DispatcherServlet without container.

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
}

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
 }

}

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

References

https://docs.spring.io/spring-framework/reference/testing/spring-mvc-test-framework/server-static-imports.html

  • Spring
  • Documentation
  • References
  • Toc
  • Books
  • Certification
  • AOP
  • Config
  • Java
  • Java core
  • JDBC
  • JPA
  • Rest
  • Security
  • Spring
  • Spring Boot
  • Spring Core
  • Spring Data
  • Spring MVC
  • Spring Rest
  • Spring Security
  • Tests
  • Transactions
  • Uncategorized

Recent Posts

  • Spring Annotations
  • Java Tests
  • Java operators
  • Java versions
  • Java Oracle Licenses
  • Configuration properties
  • MockMvc
  • Spring Security III
  • MVC Controller Method Params
  • JPA Methods
  • Transaction propagation and isolation
  • Spring JDBC
  • Spring Boot Auto-Configuration
  • Spring Resource interface
  • JSR 330 Standard Annotations
  • Spring Aware Interfaces
  • Spring Transactions
  • Spring Boot Core
  • MVC Rest
  • Spring Boot JPA
©2025 Spring Framework Blog | Built using WordPress and Responsive Blogily theme by Superb