您可以使用匹配器 ( http://code.google.com/p/hamcrest ) 来检查您是否将正确的参数传递给您的方法。请注意,您需要静态导入匹配器(在我的示例中为 HasCorrelationId)。
下面的示例断言 client.forwardMessage(m) 被调用一次,带有空相关 ID 的消息和一次带有相关 ID =“abc”的消息。
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
public class HasCorrelationId extends TypeSafeMatcher<Message> {
private final Object expectedCorrelationId;
public HasCorrelationId(Object expectedCorrelationId) {
this.expectedCorrelationId = expectedCorrelationId;
}
@Override
public boolean matchesSafely(Message message) {
if (expectedCorrelationId==message.getCorrelationId()) return true;
return expectedCorrelationId==null? false: expectedCorrelationId.equals(message.getCorrelationId());
}
public void describeTo(Description description) {
description.appendText("hasCorrelationId("+expectedCorrelationId+")");
}
public static HasCorrelationId hasCorrelationId(Object correlationId) {
return new HasCorrelationId(correlationId);
}
}
...现在进行测试:
public class MyTest {
private Mockery context = new Mockery();
@Test
public void testCorrelationId() {
final Client client = context.mock(Client.class);
final Message message1 = context.mock(Message.class,"message1");
final Message message2 = context.mock(Message.class,"message2");
context.checking(new Expectations(){{
allowing(message1).getCorrelationId();will(returnValue(null));
allowing(message2).getCorrelationId();will(returnValue("abc"));
one(client).forwardMessage(with(hasCorrelationId(null)));
one(client).forwardMessage(with(hasCorrelationId("abc")));
}});
client.forwardMessage(message1);
client.forwardMessage(message2);
}
}