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

标签 java junit 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

最佳答案

您可以按照以下步骤进行

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/

相关文章:

java - Eclipse plugin\Java Library 创建流程图

java.lang.NoClassDefFoundError : org/hamcrest/SelfDescribing

java - 在 Camel 中模拟文件端点

java - 在 java/junit 中组织单元测试,用于使用通用 api 测试类

java - 汉克雷斯特。将集合中的项目与 2 个特定属性值匹配

java - 标准 Hamcrest 匹配器检查集合是否为空或 null?

java - OsgiPlugin - 插件从未解决服务错误

java - 使用值而不是占位符保存到文件中

java - 按钮未按预期协调

java - Junit,测试,Flyway : Can you combine @Before and @Flyway annotations?