Ela*_*da2 7 java equals hamcrest matcher
我想运行这行代码:
assertThat(contextPin.get(), equalTo(pinPage.getPinObjFromUi()));
但我想打印到日志提供信息
这意味着我可以知道哪些字段不相等.
所以我想过要实现一个匹配器.
我用Google搜索了,但无法正确编写
因为我的方法无法将对象actual和expected对象组合在一起.
这是我的代码:
我该怎么写干净呢?
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;
}
}
Run Code Online (Sandbox Code Playgroud)
尝试更多类似这样的事情:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
您的匹配项应该expected在构造函数中接收,并将其与item传递给 的“实际值”参数进行比较matchesSafely。你不应该覆盖matches.
这将符合预期assertThat:
assertThat(actual, matcher-using-expected);
Run Code Online (Sandbox Code Playgroud)
我认为基于字符串的匹配器是类型安全的,并且将提供一个很好的例子。
| 归档时间: |
|
| 查看次数: |
6786 次 |
| 最近记录: |