方法调用的验证在单元测试中失败

时间:2015-08-14 13:46:32

标签: java junit mockito

我的测试类:

 @Before
  public void init() {
    arg2= mock(Dispatcher.class);  
    target = new FileHandlerImpl(Dispatcher, service , channel, scope);
  }

  @Test
  public void shouldVerifyCalls() throws Exception {
    final String arg1 = "Some arg 1";
    final String arg3 = "Some arg 3";
    final String arg4 = "Some arg 4";
    target.handleMessage(message, endpointSession);  
    verify(arg2).send(arg1, arg2, arg3, arg4); //here is error
}

错误日志:

Argument(s) are different! Wanted:
Dispatcher.send(
    "179fb6c5-9e47-41cc-9903-d0df5a317f55",
    Mock for Dispatcher, hashCode: 992040402,
    null,
    null
);
-> at com.TestApp.FileHandlerTest.shouldVerifyCalls(FileHandlerTest.java:77)
Actual invocation has different arguments:
Dispatcher.send(
    "d6723004-45aa-4958-8a8e-595a01056c82",
    Dispatcher{id=100, serial='null', sentTime=1, priority=99},
    null,
    null
);

1 个答案:

答案 0 :(得分:0)

你必须使用Mockito的[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext=false)] public class MyService : IMyService 来达到你想要的效果。我相信这个例子将澄清这个概念:

Matchers

如果你想确保只调用一次方法,你也可以使用:

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

...

List<String> mockedList = mock(List.class);
mockedList.add("test");

// this won't fail the test because the parameters match
verify(mockedList).add("test");

// this will fail the test because Mockito verifies the parameters and they don't match
verify(mockedList).add("other string");

// on the other hand, if you don't care about the parameters, you can use Matchers
verify(mockedList).add(anyString());
// or more generically
verify(mockedList).add(any(String.class));