异常org.mockito.exceptions.verification.TooManyActualInvocations解决方案

今天使用PowerMock写了一段单测代码,

我的代码如下:

Mockito.verify(entitySubscribeDao).addEntitySubscribe(Mockito.any(EntitySubscribe.class));

报错如下:

写道
org.mockito.exceptions.verification.TooManyActualInvocations:
entitySubscribeDao.addEntitySubscribe(<any>);
Wanted 1 time:
-> at org.kanpiaoxue.dmeta.service.impl.EntitySubscribeServiceImplTest.testSubscribeEntity(EntitySubscribeServiceImplTest.java:296)
But was 2 times. Undesired invocation:
-> at org.kanpiaoxue.dmeta.service.impl.EntitySubscribeServiceImpl.subscribeEntity(EntitySubscribeServiceImpl.java:251)

异常信息说明我的单测代码应该被调用2次,而我实际上只调用了1次。

该如何解决呢?

代码如下:

Mockito.verify(entitySubscribeDao,Mockito.times(2)).addEntitySubscribe(Mockito.any(EntitySubscribe.class));

 参考来自: 

http://stackoverflow.com/questions/14889951/how-to-verify-a-method-is-called-two-times-with-mockito-verify

内容如下:

I want to verify if a method is called twice or more than once through mockito verify. I used verify and it complains like this:

org.mockito.exceptions.verification.TooManyActualInvocations: 
Wanted 1 time:
But was 2 times. Undesired invocation:
share improve this question
 

1 Answer

up vote 109 down vote accepted

Using the appropriate VerificationMode, of course:

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");
share improve this answer
 
1  
@Lioan -- You should change the second verify to use the argument times(3). –  Dustin B.  Aug 12 '13 at 18:08 
    
@DustinB. Whoops, of course. Changed it. –  Liosan  Aug 13 '13 at 6:42
1  
For those who don't already have the static import, the full version of times(...) isVerificationModeFactory.times(...). –  Steve Chambers  Aug 27 at 8:03 
    
You can also use Mockito.times(...) instead of VerificationModeFactory.times(...) for the static import –  Wim Deblauwe  Nov 24 at 10:16

猜你喜欢

转载自kanpiaoxue.iteye.com/blog/2264052