为什么 MVC 中的单元测试比 MVP 和 MVVM 更难

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

我一直在研究 MVC/MPV/MVVM 的优缺点,一个共同的主题是 MVC 比 MVP 和 MVVM 更难进行单元测试,但我不完全理解为什么。

根据我目前的理解,在 MVC 中,视图依赖于模型和控制器,因此要测试视图,必须模拟控制器和模型。 MVP/MVVM 对此有何改进?

在 MVC 中,没有单独的组件来处理 UI 或表示逻辑。大多数时候,它是写在View层的(Eg. Activity)。你必须依赖框架,比如 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 博客解释得更详细。

我建议探索 Guide to app architecture and Clean architecture 以构建高度模块化和可测试的应用程序。

MVPMVC 相比,

MVVM 是实现单元测试的最佳选择,因为您可以为 ViewModelModel 编写测试用例]层而不需要引用视图和模拟它的对象。

MVP 也是一个很好的架构模式,但与 MVVM 相比,它的弱点是您在 Presenter 层中引用了视图,因此您需要在 Presenter 单元测试中与视图引用作斗争.

MVC 测试几乎与 MVP 类似,但它的主要问题是您不仅可以访问 Controller 层中的 View,还可以访问Model 层在你的 View 中也让你的测试更难。

总的来说,尽可能多地解耦你的代码,编写单元测试会更容易,而 MVVM 架构在很大程度上提供了这种解耦。