How To Unit Test A Get REST Service Using Mockito With JUnit

Posted By : Kaushlendra Kumar Pal | 27-May-2018

In Unit Testing, if we require to test REST Services then there is no need to launch the full application but we can launch only the specific controller which components we are testing.

In spring MVC application we can use WebMvcTest annotation for unit testing when a test focuses only on Spring MVC components.

 

Now we will see some most important annotations that we can use for Unit Test on Rest Services:

1. @RunWith ( SpringRunner.class ):  Here we used SpringRunner to launch Spring TestContext framework with the @RunWith annotation.

 

2. @WebMvcTest ( value = EmployeeController.class, secure = false ): Here @WebMvcTest annotation will launch only EmployeeController for Unit Test.

 

3. @Autowired private MockMvc mockMvc: Here we autowired MockMvc to execute requests, it is basically an entry point for Server Side test.

 

4. @MockBean private EmployeeService employeeService: Here we are creating MockBean of EmployeeService for the unit tests of EmployeeController it will add mock of the EmployeeService to the ApplicationContext.

 

5. Mockito .when(employeeService.retrieveProjecteDetails(Mockito.anyString(),Mockito.anyString())) .thenReturn(mockProject): Here we are mocking retrieveProjecteDetails method from employeeService which will return a mockProject when invoked.

 

6. MockMvcRequestBuilders .get("/employee/Emp1/project/Project1") .accept(MediaType.APPLICATION_JSON): Here by using MockMvcRequstBuilder we can execute a GET request to the particular URI with accept header "application/json".

 

7. mockMvc.perform(requestBuilder).andReturn(): Here this statement is used to send the request to the controller and get the response back.

 

8. JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false): This will allow to do a partial assert for the JSON String.

 

Suppose we have a following GET Rest Service:

In the EmployeeController which exposes a couple of getting services in which one of these is exposing a Get Service for retrieving specific ProjecteDetails of an employee.

@GetMapping("/employee/{employeeId}/project/{projectId}"): Suppose this is a Get Service to retrieve ProjecteDetails of an employee.

 

Test by executing the GET Service Using Postman:

We will hit a request to http://Your-Domain/employee/Emp1/project/Project1 to test the service and we get the response is as shown below.

{
  "id": "Project1",
  "name": "Spring-Boot Project",
  "description": "Data Management",
  "technologies": [
    "Spring-Boot",
    "AngularJS",
    "MongoDb",
    "Java"
  ]
}

 

The following example will show you how to apply Unit Test on above GET service:

@RunWith(SpringRunner.class)
@WebMvcTest(value = EmployeeController.class, secure = false)
public class EmployeeController {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private EmployeeService employeeService;

    Course mockProject = new Course("Project1", "Spring-Boot Project", "Data Management",Arrays.asList("Spring-Boot", "AngularJS", "MongoDb","Java"));

    @Test
    public void testRetrieveProjecteDetails() throws Exception {

        Mockito.when(employeeService.retrieveProjecteDetails(Mockito.anyString(),Mockito.anyString())).thenReturn(mockProject);

        RequestBuilder requestBuilder = MockMvcRequestBuilders
                .get("/employee/Emp1/project/Project1")
                .accept(MediaType.APPLICATION_JSON);

        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        System.out.println(result.getResponse());

        String expected = "{id:Project1,name:Spring-Boot Project,description:Data Management}";

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

 

I hope you have got something useful information from this blog.

 

Related Tags

About Author

Author Image
Kaushlendra Kumar Pal

Kaushlendra is an experienced Java Developer with comprehensive mastery of all Java packages. Able to Write well designed, testable, efficient code as per the requirements and handle different types of issues as well as functions.

Request for Proposal

Name is required

Comment is required

Sending message..