Mockito - 验证方法是否重启次数?
Mockito - Does verify method reboot number of times?
如果我们有这个代码:
@Test
public void test1(){
Interface1 i1 = mock(Interface1.class)
method1(); // This method calls i1.mockedmethod()
verify(i1, times(1)).mockedmethod();
method1();
verify(i1, times(2)).mockedmethod();
}
我知道它会通过第一个验证,但我对第二个有疑问。 verify 方法是计算该方法被调用的所有次数还是仅计算自上次验证以来的次数?
创建后,模拟将记住所有交互。然后您可以有选择地验证您感兴趣的任何交互。
这意味着您的 mock 会在您每次调用您想要的方法时计数,并且在您调用 verify
时不会重置。
如果您想了解更多相关信息,请阅读此内容(
这是我找到这些信息的地方):
http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html
Mockito 会记住,所以它从第一次交互开始算起,不会重置。
此外,请注意 verify(i1, times(1)).mockedmethod();
与 verify(i1).mockedmethod();
相同。
有关 mockito 的更多信息 here。
请注意,可以使用 Mockito.reset(mock)
重置调用方法的时间
更新:如 t7tran 下面所建议,使用 clearInvocations(T... mocks) 将仅重置调用次数
使用 void reset(T... mocks) will reset all stubbings on the mocks. If you just need to reset the invocation counts for subsequent verifications, use void clearInvocations(T... mocks).
如果我们有这个代码:
@Test
public void test1(){
Interface1 i1 = mock(Interface1.class)
method1(); // This method calls i1.mockedmethod()
verify(i1, times(1)).mockedmethod();
method1();
verify(i1, times(2)).mockedmethod();
}
我知道它会通过第一个验证,但我对第二个有疑问。 verify 方法是计算该方法被调用的所有次数还是仅计算自上次验证以来的次数?
创建后,模拟将记住所有交互。然后您可以有选择地验证您感兴趣的任何交互。
这意味着您的 mock 会在您每次调用您想要的方法时计数,并且在您调用 verify
时不会重置。
如果您想了解更多相关信息,请阅读此内容( 这是我找到这些信息的地方):
http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html
Mockito 会记住,所以它从第一次交互开始算起,不会重置。
此外,请注意 verify(i1, times(1)).mockedmethod();
与 verify(i1).mockedmethod();
相同。
有关 mockito 的更多信息 here。
请注意,可以使用 Mockito.reset(mock)
重置调用方法的时间更新:如 t7tran 下面所建议,使用 clearInvocations(T... mocks) 将仅重置调用次数
使用 void reset(T... mocks) will reset all stubbings on the mocks. If you just need to reset the invocation counts for subsequent verifications, use void clearInvocations(T... mocks).