Qbix Qbix - 3 months ago 28
Groovy Question

assert list contains elements of given class in Spock

I have a chain manager that contains some handlers. I would like to check if it has handlers of specific classes by default. How to do that?

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
}


edit:
I've improved the code from Answer, to defend against two elements of the same class, so it is like this now:

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

Answer
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]
}