[英]Verify Mock calls in a particular test
在我的一个单元测试中,我试图验证我的一个模拟方法是否从未被调用过。 问题是这个mock是一个全局的@beforeClass
模拟,很常见于很多其他测试。
因此,当我尝试验证模拟是否从未被调用时,它总是会失败,因为其他测试正在调用mock。 有没有办法使用Mockito来验证仅针对该测试的模拟调用?
我能想到的一个解决方案是将我的常用模拟从@BeforeClass
转换为@Before
(这样在每次测试之前,都会重新创建模拟)。 但是想要检查是否有任何其他解决方案而不触及常见的BeforeClass
模拟。
@BeforeClass
public void before() {
someClassMock = mock(someClass.class);
when(someClassMock.aMethodCall(any()).thenReturn(true);
}
// Bunch of tests
@Test
public void oneOfTheManytest(){
//some code where someClassMock.aMethodCall is NOT called
verify(someClassMock, never()).aMethodCall(any());
// ^^ This always fails, even when I am sure this mock
// is not called for this test.
// I think this looks if this mock is called or not overall for this test file.
}
有人可以帮助解决我可以验证特定测试的模拟方法调用的解决方案吗?
我可以在这里推断出你的测试不遵循AAA。 每个测试都应该单独运行,并且它的成功不应该取决于其他测试的执行。
您最好的选择是将需要重复的模拟设置提取到辅助方法中,并在测试的排列部分中调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.