如何使用Hamcrest比较不同类型

时间:2019-08-21 11:23:05

标签: java hamcrest

我尝试比较不同类型的火腿肠。但是我不明白,如何为以下问题构建自己的<button class="switcher switcher__Last collapsible">X1</button> <div class="collapsibleContent"> <span class="choise__block-item">Text</span> <span class="choise__block-item">Text</span> <span class="choise__block-item">Text</span> </div> <button class="switcher switcher__Last collapsible">X2</button> <div class="collapsibleContent"> <span class="choise__block-item">Text</span> <span class="choise__block-item">Text</span> <span class="choise__block-item">Text</span> </div>

Matcher

String[] exp = new String[]{"x", "y", "z"}; DAO[] cur = getFromExternalWebservice(); Assert.assertThat("wrong strings", exp, Matchers.arrayContainingInAnyOrder(cur)); 是以下类的数组:

cur

上面的测试实际上应该比较class DAO { public String id; public String name; } 中的Strings和数组expname个对象的DAO属性。我无法在cur上进行任何更改(例如添加DAO方法)。

我可以将Web服务的结果转换为toString()数组,将其发送给Matcher,如下所示:

names

但这很丑陋,我如何构建一个String names[] = new String[cur.length]; for (int i = 0; i < cur.length; i++) { names[i] = cur[i].name; } Assert.assertThat("wrong strings", exp, Matchers.arrayContainingInAnyOrder(names)); 来比较Matcher而没有任何数据副本?

1 个答案:

答案 0 :(得分:0)

我实现了第一个想法:

public class IsIn extends BaseMatcher<String> {

   class DAOIterator implements Iterable<String>, Iterator<String> {
        private final DAO[] collection;
        private int idx;

        public DAOIterator(DAO[] elements) {
            this.collection = elements;
            idx = 0;
        }

        @Override
        public boolean hasNext() {
            return (this.collection.length > this.idx);
        }

        @Override
        public String next() {
            return this.collection[this.idx++].name;
        }

        @Override
        public Iterator<String> iterator() {
            return new DAOIterator(this.collection);
        }
    }

    private final DAO[] collection;

    public IsIn(DAO[] elements) {
        this.collection = elements;
    }

    @Override
    public boolean matches(Object o) {
        for (DAO d : this.collection) {
            if (o == null ? d.name == null : o.equals(d.name)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void describeTo(Description buffer) {
        buffer.appendText("one of ");
        buffer.appendValueList("{", ", ", "}", new DAOIterator(this.collection));
    }

}

在JUnit测试用例上调用它:

String[] exp = new String[]{"x", "y", "z"};
DAO[] cur = getFromExternalWebservice();
Assert.assertThat("wrong strings", Arrays.asList(exp), Matchers.everyItem(new IsIn(cur)));