Szy*_*pek 9 java hamcrest matcher mockito
我需要编写Matcher来检查多个属性.对于我使用的单一财产:
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
Matcher<Class> matcherName = Matchers.<Class> hasProperty("propertyName",equalTo(expectedValue));
Run Code Online (Sandbox Code Playgroud)
我怎么想在一个匹配器中查看更多属性?
Rub*_*ben 16
您可以通过将匹配器与allOf以下内容组合使用一个匹配器来检查更多属性:
Matcher<Class> matcherName = allOf(
hasProperty("propertyName", equalTo(expected1)),
hasProperty("propertyName2", equalTo(expected2)));
Run Code Online (Sandbox Code Playgroud)
但我想你实际上正在寻找的是那个samePropertyValuesAs,通过检查属性本身而不是equals方法来检查bean是否具有与另一个相同的属性值:
assertThat(yourBean, samePropertyValuesAs(expectedBean));
Run Code Online (Sandbox Code Playgroud)
Ruben's answer using allOf is the best way to combine matchers, but you may also choose to write your own matcher from scratch based on BaseMatcher or TypeSafeMatcher:
Matcher<Class> matcherName = new TypeSafeMatcher<Class>() {
@Override public boolean matchesSafely(Class object) {
return expected1.equals(object.getPropertyName())
&& expected2.equals(object.getPropertyName2());
}
};
Run Code Online (Sandbox Code Playgroud)
Though you do get unlimited power to write arbitrary matcher code without relying on reflection (the way that hasProperty does), you'll need to write your own describeTo and describeMismatch(Safely) implementations to get the comprehensive error messages that hasProperty defines and that allOf would aggregate for you.
You may find it wise to use allOf for simple cases involving a couple of simple matchers, but consider writing your own if matching a large number of properties or if implementing complex conditional logic.
| 归档时间: |
|
| 查看次数: |
7835 次 |
| 最近记录: |