02 Aug

Junit Testing Spring REST Services

In this tutorial we will see how to write Junit test cases on Spring REST services. Before continue to reading this tutorial please read first Spring RESTful Webservice CRUD Example

We have total four operations on this REST example. If you want you may add more operation such as find all products and apply Junit on it.

The complete Junit class is given below

We have used MockitoJunitRunner to run the Junit test cases. We have mocked the service class and we have used annotation @Spy and @InjectMocks on Controller class because we want to call the method of the real object and we want to inject the mocked objects into Controller respectively.

We have also used MockMvc object, which is a main entry point for server-side Spring MVC test support.

In test case method testGetProductById() we expect to return only one product from the controller method operation GET. So we have verified using the mockMvc.perform() and we don’t need any extra assertion for that.

In the test case method testSaveProduct() we expect the response status 201 and here we are returning result from mockMvc.perform() and after that we verifying the status. But if we would not have returned the result from the specified method we could have verified using the same way as we have verified for GET operation.

In test case method testUpdateProduct() we have tested the PUT operation and verified the status 200. Here we could have returned the result from mockMvc.perform() and verified using assertion but we verified at the same place while we are performing PUT operation using mockMvc.perform().

In test case method testDeleteProductByid() for DELETE operation we verified the status in the same way as PUT operation.

Thanks for reading.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

Share