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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With