Spock数据驱动测试用类来测试“instanceof”断言

时间:2017-06-24 19:09:43

标签: unit-testing groovy spock

我有一个测试,我想测试一个特定的结果是一种类。 使用 instanceof 关键字断言。遗憾的是,我没有想出如何在数据表中实际提供数据值 expectedClass ,而没有使用 instanceof 实际调用它的问题。我认为关键字 instanceof 是这里的问题,因为它只接受类/接口名称。知道如何以其他方式测试我想测试的内容吗?

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

    }
}

2 个答案:

答案 0 :(得分:7)

你可以这样使用isCase

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

    }
}

答案 1 :(得分:5)

正如tim_yates所说,你可以使用groovy函数isCase或java函数isAssignableFrom,或者你可以使用groovy in关键字(委托给isCase)。

  • expectedClass.isCase(battleResolver)
  • expectedClass.isAssignableFrom(battleResolver)
  • expectedClass in battleResolver