我想检查何时使用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);


这是编译错误:

java - 我怎么称呼一个自定义的hamcrest Matcher?-LMLPHP

最佳答案

这是您可以如何进行

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))
);

07-24 09:23