Hamcrest Pattern断言自定义集合的2个属性

时间:2017-08-25 15:44:12

标签: java junit4 hamcrest assertthat

我有一个带有两(2)个属性的Java自定义对象集合List<Employee>。它是作为Web服务的响应而收到的。对象好像是

public class Employee{
   public String getName(){ ... }
   public String getDesignation(){ ... }
}

我需要写一个断言来检查员工的姓名是否 David ,然后其名称必须是经理。我试着这样做

assertThat(employeeList, allOf(hasItem(hasProperty("name", equalTo("David"))) , hasItem(hasProperty("designation", equalTo("Manager")))));

但如果至少有一个Manager实例和一个David,它就会通过。我的要求是在单个实例上应用这两个检查。

请帮忙。

1 个答案:

答案 0 :(得分:2)

鉴于课程Foo

public class Foo {
    private String name;
    private String designation;

    public Foo(String name, String designation) {
        this.name = name;
        this.designation = designation;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }
}

自定义Hamcrest匹配器:

private static class FooMatcher extends BaseMatcher<List<Foo>> {
    public String name;
    public String designation;

    public static FooMatcher matches(String name, String designation) {
        return new FooMatcher(name, designation);
    }

    private FooMatcher(String name, String designation) {
        this.name = name;
        this.designation = designation;
    }

    @Override
    public boolean matches(Object item) {
        Foo foo = (Foo) item;
        return foo.getName().equals(name) && foo.getDesignation().equals(designation);
    }

    @Override
    public void describeTo(Description description) {
        // this is a quick impl, you'll probably want to fill this in!
    }
}

此测试将通过:

@Test
public void canAssertOnMultipleFooAttributes() {
    List<Foo> incoming = Lists.newArrayList(new Foo("bill", "sir"), new Foo("bob", "mr"), new Foo("joe", "mr"));
    assertThat(incoming, hasItem(FooMatcher.matches("bob", "mr")));
}