Spock data driven testing with classes to test for "instanceof" assertions
Asked Answered
B

2

6

I have a test where I want to test a specific result to be of a kind of a class. Asserting this with the instanceof keyword. Sadly I did not figured out how to actually provide a data value expectedClass in the data table without having a Problem to actually call it with instanceof. I think the keyword instanceof is the issue here because it only accepts class/interface names. Any idea how I can test what I want to test in another way?

class BattleResolverFactoryTest extends Specification {

    def uut = new BattleResolverFactory()

    @Unroll
    def "should return proper BattleResolver for given ConflictType"(Conflict.ConflictType conflictType, Class<? extends BattleResolver> expectedInstance) {
        when:
        def battleResolver = BattleResolverFactory.getResolver(conflictType)
        then:
        battleResolver instanceof expectedClass
        where:
        conflictType                            | expectedClass
        Conflict.ConflictType.INFANTRY_CONFLICT | TestInfantryResolver
        Conflict.ConflictType.ARMOR_CONFLICT    | TestArmorResolver

    }
}
Boxthorn answered 24/6, 2017 at 19:9 Comment(0)
S
9

You can use isCase like so:

class BattleResolverFactoryTest extends Specification {

    def uut = new BattleResolverFactory()

    @Unroll
    def "should return proper BattleResolver for given ConflictType"(Conflict.ConflictType conflictType, Class<? extends BattleResolver> expectedInstance) {
        when:
        def battleResolver = BattleResolverFactory.getResolver(conflictType)

        then:
        expectedClass.isCase(battleResolver)

        where:
        conflictType                            | expectedClass
        Conflict.ConflictType.INFANTRY_CONFLICT | TestInfantryResolver
        Conflict.ConflictType.ARMOR_CONFLICT    | TestArmorResolver

    }
}
Slipon answered 24/6, 2017 at 19:13 Comment(0)
E
8

As tim_yates said you can use the groovy function isCase or the java function isAssignableFrom, or you could use the groovy in keyword (which delegates to isCase).

  • expectedClass.isCase(battleResolver)
  • expectedClass.isAssignableFrom(battleResolver)
  • expectedClass in battleResolver
Enterogastrone answered 25/6, 2017 at 1:55 Comment(1)
in the case of the in keyword, the usage would be reversed. It would actually be battleResolver in expectedClassAllfired

© 2022 - 2024 — McMap. All rights reserved.