我想检查何时使用 realtimeUpdate
调用模拟,其中 currentTime
字段等于某个 LocalDateTime
:
我想使用自定义匹配器运行此类代码:
verify(mockServerApi).sendUpdate(new TimeMatcher().isTimeEqual(update, localDateTime2));
但是当我尝试使用此自定义匹配器运行时出现编译错误。
我该如何解决这个问题?
public class TimeMatcher {
public Matcher<RealtimeUpdate> isTimeEqual(RealtimeUpdate realtimeUpdate, final LocalDateTime localDateTime) {
return new BaseMatcher<RealtimeUpdate>() {
@Override
public boolean matches(final Object item) {
final RealtimeUpdate realtimeUpdate = (RealtimeUpdate) item;
return realtimeUpdate.currentTime.equalTo(localDateTime);
}
这是方法签名
void sendRealTimeUpdate(RealtimeUpdate realtimeUpdate);
这是编译错误:
最佳答案
您可以按照以下步骤进行
类TimeMatcher
,您只需要LocalDateTime
public class TimeMatcher {
public static Matcher<RealtimeUpdate> isTimeEqual(final LocalDateTime localDateTime) {
return new BaseMatcher<RealtimeUpdate>() {
@Override
public void describeTo(final Description description) {
description.appendText("Date doesn't match with "+ localDateTime);
}
@Override
public boolean matches(final Object item) {
final RealtimeUpdate realtimeUpdate = (RealtimeUpdate) item;
return realtimeUpdate.currentTime.isEqual(localDateTime);
}
};
}
}
测试:
Mockito.verify(mockRoutingServerApi).sendRealTimeUpdate(
new ThreadSafeMockingProgress().getArgumentMatcherStorage()
.reportMatcher(TimeMatcher.isTimeEqual(localDateTime2))
.returnFor(RealtimeUpdate.class));
您需要使用 returnFor
提供 RealtimeUpdate
参数类型,正如 sendRealTimeUpdate
所期望的那样
这相当于:
Mockito.verify(mockRoutingServerApi).sendRealTimeUpdate(
Matchers.argThat(TimeMatcher.isTimeEqual(localDateTime2))
);
关于java - 我如何调用自定义 hamcrest 匹配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37818059/