java验证特定测试中的模拟调用
在我的一个单元测试中,我试图验证我的一个模拟方法是否从未被调用。问题是这个mock是一个全局的@beforeClass
mock,在很多其他测试中都很常见
因此,当我尝试验证是否从未调用过mock时,它总是失败,因为其他测试正在调用该mock。有没有一种方法可以使用Mockito只为该测试验证mock调用
我能想到的一个解决方案是将我的公共mock从@BeforeClass
转换为@Before
(以便在每次测试之前,重新创建mock)。但是想检查是否有其他解决方案,而不涉及常见的BeforeClass
mock
@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.
}
有人能帮我找到一个解决方案,让我验证特定测试的模拟方法调用吗
# 1 楼答案
我可以推断你的测试不符合AAA标准。每个测试都应该可以单独运行,它的成功不应该依赖于其他测试的执行
最好的办法是将需要重复的模拟设置提取到helper方法中,并在测试的arrange部分调用它