如何实现hamcrest匹配器 [英] how to implement a hamcrest matcher

查看:77
本文介绍了如何实现hamcrest匹配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要运行以下代码行:

assertThat(contextPin.get(),equalTo(pinPage.getPinObjFromUi()));

但我想打印到日志中以提供更多信息

but I want to print to the log be informative

表示我可以知道哪些字段不相等.

meaning that I could know which fields were not equal.

所以我考虑过实现匹配器.

So I have thought to implement a matcher.

我已经用谷歌搜索了,但是写不正确

I have googled it, but couldn't write it properly

因为我的方法无法将 actual expected 对象放在一起.

as my method couldn't get the actual and expected objects together.

这是我的代码:

我怎么写得干净?

public class PinMatcher extends TypeSafeMatcher<Pin> {

    private Pin actual;
    private Object item;

    public PinMatcher(Pin actual) {
        this.actual = actual;
    }

    @Override
    protected boolean matchesSafely(Pin item) {
        return false;
    }

    @Override
    public void describeTo(Description description) {

    }

//cannot override this way
    @Override
    public boolean matches(Object item){
       assertThat(actual.title, equalTo(expected.title));
return true;
    }

//cannot access actual when called like this:
// assertThat(contextPin.get(), new PinMatcher.pinMatches(pinPage.getPinObjFromUi()));
    @Override
    public boolean pinMatches(Object item){
        assertThat(actual.title, equalTo(expected.title));
return true;
    }
}

推荐答案

尝试更多类似的方法:

package com.mycompany.core;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;


public class PinMatcher extends TypeSafeMatcher<Pin> {

    private Pin actual;

    public PinMatcher(Pin actual) {
        this.actual = actual;
    }

    @Override
    protected boolean matchesSafely(Pin item) {
        return actual.title.equals(item.title);
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("should match title ").appendText(actual.title);

    }
}

这篇关于如何实现hamcrest匹配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆