Why use Spring's Mock MVC when you have unit tets of your controller classes

When it comes to the unit-testing of a Controller (or any Endpoint which is exposed) classes, there are two things that we will validate:

(1) Controller's actual logic itself as standalone i.e., right service calls are invoked or not etc..

(2) Request URL mapping and the Response status & object

Item (1) above is what we test in general with all other classes like Services, Utility classes etc..

Item (2) needs to be covered/tested additionally for the endpoints (controller classes) which have been exposed, so whether we use Spring's MockMVC or other machinery to do that, it is up to us really.

Spring's MockMVC indeed helps us to start the in-memory servlet container & check that the right controller methods are invoked & then the right responses have been coming out.

From my personal experience, testing the controllers (for item(2)) helped me to resolve URL mapping conflict issues (of course, within the same controller) etc.. straight away rather than fixing them at the later stages of the project.


Based on My experience I will try to answer your question.

First thing we need to understand why we use unit testing?

It is a extra check used by developer to write clean working code. Clean working code means every line written should be doing what it is expected to do. how do you achieve this? Here comes unit testing. The standalone unit of code you are writing should be verified standalone. Method is best part in code which represents standalone unit code template.

Unit Testing for Method

Developer should write a test for method which describes the method behavior. And possible checks that i follow is is it returning the expected value considering all positive scenarios? is it working in case of Exception? is it calling correct subsequent methods ?

Developer should verify the method by actually calling it providing a mock environment

Below is possible answer to your question. though it is solely based upon the developers.

Controller methods are intended to invoke correct service call accepting input and returning the value from service to view. So I may think of write a unit test case for controller method as you are thinking is a right approach. But you should verify the method by calling it in same way as it will be called in real time. so you need to call controller method in same way as MVC does. Hence it is better option to use MockMVC. MockMVC is also useful to verify the urls, input params , response and status which are part of controller method. Considering these all it makes it standalone unit of code.

Hope this will clarify your doubt.