Write a Unit Test for Spring Boot REST Web Services

Note: A purpose of this post is to repeat knowledge on how to unit test Restful web services in a Spring Boot applications.

What do you need to know when making a REST web request

A GET request

  • username and password or a token for authentication
  • a service URL
  • request parameters
  • some required HTTP headers

What do you need when running a test

From a list of what you need to know to be able to make a request, it defines how you gonna write your unit test

In our unit test, we want to test a @RestController component. The controller uses a @Service component which we want to ignore. Therefore, we mock the @Service component.

Below is what we need to do to create a unit test

Load a test context

Since it is a Spring Boot application, we are going to use test support functionality provided by Spring Boot and Spring Test framework

@RunWith (SpringRunner.class)

Launch the controller under test

@WebMvcTest (value = StudentController.class, secure = false)

Mock components that are not under test

The StudentController uses the service StudentService but we’re not going to test the StudentService. Therefore, we mock it.

@MockBean StudentService studentService;

@MockBean will inject a StudentService instance into an ApplicationContext.

Mockito.when(studentService.retrieveCourse(Mockito.anyString(), Mockito.anyString())).thenReturn(mockCourse);

Build a request

Use MockMvcRequestBuilders

RequestBuilder rb = MockMvcRequestBuilders.get("/students/Student1/courses/Course1").accept(MediaType.APPLICATION_JSON);

Build an expected response

String expected = "{id:Course1,name:Spring,description:\"10 Steps\"}";

Make a call

@Autowired private MockMvc mockMvc;
MvcResult result = mockMvc.perform(rb).andReturn();

Verify the result


JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: