这是个好问题!
我认为其根本原因如下,我们使用JUnit不仅仅是为了单元测试。所以这个问题应该被分解:
我应该在集成测试(或任何其他高于单元测试)中使用Mockito.verify()吗?
我应该在我的黑盒单元测试中使用Mockito.verify()吗?
我应该在白盒单元测试中使用Mockito.verify()吗?
因此,如果我们将忽略高于单元的测试,这个问题可以重新表达为“使用Mockito.verify()使用白盒单元测试在单元测试和我的could实现之间创建了很好的耦合,我可以做一些“灰盒”单元测试,我应该使用什么经验规则”。
现在,让我们一步一步地完成所有这些。
我应该在我的集成(或任何其他高于单元测试)测试中使用Mockito.verify()吗?*
我认为答案显然是否定的,而且你不应该为此使用mock。您的测试应该尽可能接近实际应用。您正在测试完整的用例,而不是应用程序的孤立部分。
*黑盒vs白盒单元测试
如果您正在使用黑盒方法,那么您实际上在做什么呢?您提供(所有等价类)输入、状态和测试,您将收到预期的输出。在这种方法中,使用mock通常是证明(你只是模仿它们正在做正确的事情;你不想测试它们),但是调用Mockito.verify()是多余的。
如果你使用白盒方法,你真正在做的是测试你的单位的行为。在这种方法中,调用Mockito.verify()是必要的,您应该验证您的单元的行为是否如您所期望的那样。
rules of thumbs for grey-box-testing
The problem with white-box testing is it creates a high coupling. One possible solution is to do grey-box-testing, not white-box-testing. This is sort of combination of black&white box testing. You are really testing the behaviour of your unit like in white-box testing, but in general you make it implementation-agnostic when possible. When it is possible, you will just make a check like in black-box case, just asserts that output is what is your expected to be. So, the essence of your question is when it is possible.
This is really hard. I don't have a good example, but I can give you to examples. In the case that was mentioned above with equals() vs equalsIgnoreCase() you shouldn't call Mockito.verify(), just assert the output. If you couldn't do it, break down your code to the smaller unit, until you can do it. On the other hand, suppose you have some @Service and you are writting @Web-Service that is essentially wrapper upon your @Service - it delegates all calls to the @Service (and making some extra error handling). In this case calling to Mockito.verify() is essential, you shouldn't duplicate all of your checks that you did for the @Serive, verifying that you're calling to @Service with correct parammeter list is sufficient.