sampig / spock

Automatically exported from code.google.com/p/spock
0 stars 0 forks source link

Class names in data variables cannot be used with "instanceof" operator #315

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
In my test, I would like to assert that created objects are instances of a 
particular class. When I provide the class name via a data variable, compiler 
gives an error "Unable to resolve class clazz". Using the data variable in 
other contexts (e.g. clazz.newInstance) works fine.

 def "test that created object is of right class"(){
        when:
        String s = "spock"
        then:
        s instanceof String
        s instanceof clazz
        where:
        clazz << [String]
    }

What version of Spock and Groovy are you using?
0.7-groovy-2.0

Original issue reported on code.google.com by cyprush...@gmail.com on 13 Jun 2013 at 8:53

GoogleCodeExporter commented 9 years ago
`s instanceof clazz` isn't valid Groovy (or Java). You'll have to use 
`clazz.isInstance(s)` instead.

Original comment by pnied...@gmail.com on 13 Jun 2013 at 11:51

GoogleCodeExporter commented 9 years ago
Thank you, Peter. I discovered that another workaround in Groovy is to use the 
"in" operator: "s in clazz" would also work correctly.

Could you explain why "s instanceof clazz" is not valid? If we assert against 
an inline class name, not a data variable, it works fine ("s instanceof 
String"). This type comparison operator is available both in Java 
(http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html) and Groovy 
(http://groovy.codehaus.org/Operators).

Original comment by cyprush...@gmail.com on 14 Jun 2013 at 10:49