断言列表包含Spock中给定类的元素

时间:2016-08-26 14:24:03

标签: unit-testing groovy spock assertions

我有一个包含一些处理程序的链管理器。我想默认检查它是否具有特定类的处理程序。怎么做?

def "contains few updaters on default"(){
    when:
        def manager = new UpdateManager();
    then:
        manager.getUpdaters().size() == 2;
        //how to check that the list contains elements of classes 
        //OneThingUpdater and OtherThingUpdater
}

编辑: 我已经改进了Answer中的代码,以防止同一类中的两个元素,所以现在就是这样:

def "contains few updaters on default"(){
    setup:
        def expectedUpdaters = [OneThingUpdater, OtherThingUpdater]
    when:
        def manager = new UpdateManager();

    then:
        def list = manager.getUpdaters()
        list.size() == 2;
        list.every {
            it.class in expectedUpdaters
            expectedUpdaters.remove(it.class)
        }
}

1 个答案:

答案 0 :(得分:4)

def "contains few updaters on default"(){
    when:
    def manager = new UpdateManager()

    then:
    def list = manager.getUpdaters()
    list.size() == 2
    list*.getClass().every { it in [OneThingUpdater, OtherThingUpdater] }

    // or, just this
    // Assuming the classes do not implement Map interface
    // getClass() can be replaced with class
    list*.class == [OneThingUpdater, OtherThingUpdater]
}