Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is unit testing harder in MVC than in MVP and MVVM

I've been doing some research on pros and cons of MVC/MPV/MVVM and one common theme is that MVC is harder to unit test than MVP and MVVM but I don't fully understand why.

From my current understanding, in MVC, the view is dependent on the model and and controller so to test the view, both the controller and the model must be mocked. How is MVP/MVVM improve on this?

like image 226
user3826764 Avatar asked Jun 20 '19 13:06

user3826764


2 Answers

In MVC, There is no separate component to handle UI or Presentation logic. Most of the time, it is written in View layer (Eg. Activity). You have to depend on frameworks like Robolectric which can understand Android ecosystem while writing unit tests. This makes difficult to unit test presentation logic. The other two patterns (MVP, MVVM) focus on decoupling Android dependencies with the help of interfaces and event driven pattern which simplifies unit testing. This blog explains more in detail.

I would suggest to explore Guide to app architecture and Clean architecture for building highly modularized and testable application.

like image 116
Jegan Babu Avatar answered Oct 24 '22 07:10

Jegan Babu


MVVM is the best choice for implementing unit tests compared with MVP and MVC because you can write test cases for both the ViewModel and Model layer without the need to reference the View and mock its objects.

MVP is also a good architecture pattern but its weakness compared with MVVM is you have reference to the View in your Presenter layer so you need to struggle with views reference in your Presenter unit tests.

MVC testing is almost like MVP but its main problem is that not only you have access to View in the Controller layer but you have access to the Model layer in your View as well that makes your testing harder.

Overall, as much as your code be decoupled writing unit tests is easier and MVVM architecture provides this decoupling to a great extent.

like image 22
Squti Avatar answered Oct 24 '22 08:10

Squti