PowerMock、EasyMock 和 Mockito 框架之间有什么区别?

What is the difference between PowerMock, EasyMock and Mockito frameworks?

我是mocking框架的新手,我的工作需要mocking框架来完成单元测试。在当前的代码库中,我可以看到以上 3 个框架在不同的地方用于单元测试。那么,我应该在上述 3 个框架中选择哪一个?

Here 你可以找到 Mockito 和 EasyMock 之间的比较:

Differences

  • No record/replay modes - no need for them. There only 2 things you can do with Mockito mocks - verify or stub. Stubbing goes before execution and verification afterwards.

  • All mocks are nice (even somehow nicer, because collection-returning methods return empty collections instead of nulls). Even though mocks are nice, you can verify them as strictly as you want and detect any unwanted interaction.

  • Explicit language for better readability: verify() and when() VS the mixture of expect(mock.foo()) and mock.foo() (plain method call without expect). I'm sure some of you will find this argument subjective :)

  • Simplified stubbing model - stubbed methods replay all the time with stubbed value no matter how many times they are called. Works exactly like EasyMock's andStubReturn(), andStubThrow(). Also, you can stub with different return values for different arguments (like in EasyMock).

  • Verification of stubbed methods is optional because usually it's more important to test if the stubbed value is used correctly rather than where's it come from.

  • Verification is explicit - verification errors point at line of code showing what interaction failed.

  • Verification in order is flexible and doesn't require to verify every single interaction.

  • Custom argument matchers use hamcrest matchers, so you can use your existing hamcrest matchers. (EasyMock can also integrate with Hamcrest though it is not a part of EasyMock but Hamcrest. See the documentation of Hamcrest).

PowerMock 是 Mockito 或 EasyMock 等其他 Mocking 框架的扩展,具有更强大的功能。这意味着您可以将 Mockito/EasyMock 和 PowerMock 组合到同一个单元测试中。

我个人使用 Mockito 对我的大部分代码进行单元测试,而 PowerMock 仅在需要其额外功能作为测试静态方法的代码中使用。

我给你一个其他人可能不喜欢的解释,但我(以及我向很多人提到过)find/found 非常有帮助:PowerMock 是模拟框架......你最好不要使用。

PowerMock 的主要优势 是您可以使用它来测试 EasyMock 可以测试的某些构造(例如 static 方法调用) '嘲笑。因此:当您想测试无法更改的第 3 方代码时;并且包含静态调用;那么你可能会转向 PowerMock。

但是当你自己写代码的时候,你会专注于writing testable code;那么你会发现"need to use PowerMock"绝对等于"you did a bad job designing your code"。例如,使用 static 会直接导致您的 类 之间 直接耦合 ;因此一旦进入就很难摆脱它。

不要误会我的意思——PowerMock 在测试中占有一席之地;但其强大的功能需要付出一定的代价。

在 EasyMock / Mockito 上:主要是 "two different ways" 编写测试用例;后者导致许多人发现更容易阅读的测试;而 EasyMock 和 "strict" 模拟允许编写测试用例,这些用例将在生产代码中的大多数更改中快速中断(它本身可能非常有用,也可能非常烦人)。

如果您控制自己的设计,那么您应该对 Mockito 基本满意。 例如,PowerMock 允许您模拟一个看起来很酷的私有成员,但如果您将该私有成员重构为通过依赖注入提供的参数,则没有必要。