有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何调用自定义hamcrest匹配器?

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

这就是编译错误:

enter image description here


共 (1) 个答案

  1. # 1 楼答案

    以下是您可以继续操作的方法

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