2016-02-16 63 views
2

我需要编写匹配器将检查多个属性。对于我用过的单个房产:匹配在一个匹配器多个属性

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

我如何在一个匹配器中检查更多属性?

回答

8

您可以检查使用一个匹配的匹配器与allOf结合多个属性:

Matcher<Class> matcherName = allOf(
     hasProperty("propertyName", equalTo(expected1)), 
     hasProperty("propertyName2", equalTo(expected2))); 

但我想,你实际上是在寻找的是samePropertyValuesAs一个,来检查,如果一个bean具有相同的属性值作为另一个通过检查属性本身,而不是equals方法:

assertThat(yourBean, samePropertyValuesAs(expectedBean)); 
+0

是,allOf是很好的方式,但我不能使用assertThat 我需要验证,如果对象run方法与预期的参数,如: '验证(模拟)。方法(argThat(matcherName));' – Szympek

+0

@Szympek 'samePropertyValuesAs'也是'Matcher'可以分配给一个变量:'匹配器 matcherName = samePropertyValuesAs(expectedBean)' – Ruben

1

Ruben's answer使用allOf是最好的方式结合匹配器,但你也可以选择基于BaseMatcherTypeSafeMatcher从头开始写自己的匹配:

Matcher<Class> matcherName = new TypeSafeMatcher<Class>() { 
    @Override public boolean matchesSafely(Class object) { 
    return expected1.equals(object.getPropertyName()) 
     && expected2.equals(object.getPropertyName2()); 
    } 
}; 

虽然你得到无限的权力来写任意匹配代码,而不依赖于反射(在该hasProperty做方式),你需要编写自己的describeTodescribeMismatchSafely)实现,以获得全面的错误消息hasProperty定义和allOf会集结你。

对于涉及几个简单匹配器的简单案例,您可能会发现使用allOf是明智的做法,但如果匹配大量属性或实现复杂条件逻辑,请考虑编写自己的代码。