Posts Spring Boot Test for RestController
Post
Cancel

Spring Boot Test for RestController

Spring Boot provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules: spring-boot-test contains core items, and spring-boot-test-autoconfigure supports auto-configuration for tests. Most developers use the spring-boot-starter-test “Starter”, which imports both Spring Boot test modules as well as JUnit, AssertJ, Hamcrest and a number of other useful libraries.

In this article we are going to see how we are going to write tests for @RestController.

Testing Web Layer

We are writing tests to the following RestContoller. As most of the controllers it doesn’t have much stuff going on here other than calling a service’s method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RestController
public class CustomerContoller {
	
	@Autowired
	private CustomerService customerService;
	
	 @GetMapping("/customers/{id}")
	public Customer getCustomer(@PathVariable String id) {
		 
		 return customerService.getCustomer(id);
		
	}

}

For testing the web layer we can use @WebMvcTest annotation, by using this, Spring Boot instantiates only the web layer rather than the whole context. In an application with multiple controllers, you can even ask for only one to be instantiated by using an attribute to the annotation, for example, @WebMvcTest(CustomerController.class).

We use @MockBean to create and inject any service our contoller uses and we set its expectations using Mockito. In the following example we are mocking the behaviour of CustomerService.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@WebMvcTest
@Import(CustomerService.class)
public class CustomerControllerTest {

	@MockBean
	CustomerService customerService;

	@Autowired
	private MockMvc mockMvc;

	@Test
	public void shouldReturnDefaultMessage() throws Exception {

		Customer customer = new Customer();
		customer.setId("123");
		customer.setFirstName("John");
		customer.setLastName("Miller");

		Mockito.when(customerService.getCustomer("123")).thenReturn(customer);
		this.mockMvc.perform(get("/customers/123")).andDo(print()).andExpect(status().isOk());

	}

}

In this article we learned about how to test Spring boot web layer with JUnit and Spring MockMvc and have used Spring Boot to isolate the web layer and load a special application context. You can have a look at the example code in my github repository

This post is licensed under CC BY 4.0 by the author.