2

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

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

我需要写一个断言来检查员工的名字是否是David那么它的指定必须是Manager。我这样试过

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

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

请帮忙。

4

1 回答 1

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")));
}
于 2017-08-25T15:56:18.783 回答