Skip to content

GroovyCastException when invoking TestFor generated getters in tests #10363

@dpcasady

Description

@dpcasady

Task List

  • Steps to reproduce provided
  • Stacktrace (if present) provided
  • Example that reproduces the problem uploaded to Github
  • Full description of the issue provided (see below)

Steps to Reproduce

  1. Create a Grails artefact (domain, controller, or service) with a property of name, or a getName() method.
  2. Create a test that references the artefact as the class under test with the @TestFor annotation.
  3. Invoke the generated getter for the artefact in the test (getDomain(), getController(), getService()).

Expected Behaviour

For artefacts that don't have a name property there are no problems and an instance of the artefact is returned by the getter. I would expect the same to hold true if there is a name property.

Actual Behaviour

Instead, the getter throws a GroovyCastException. For a domain class, Bar:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'class foo.Bar' with class 'java.lang.Class' to class 'foo.Bar'
	at foo.BarSpec.class under test getter throws exception(BarSpec.groovy:11)

From what I can tell, the exception is thrown in the getter method in the process of checking if the bean exists in the application context. I've tried decompiling the compiled test and for an artefact without a name property, the AST generated code looks something like this:

applicationContext.containsBean(Bar.class.getName())

For an artefact with the name property, the AST generated code looks like this:

applicationContext.containsBean(((Bar)ScriptBytecodeAdapter.castToType((Object)Bar.class, (Class)Bar.class)).getName())

This seems to be the cast that is throwing the exception. The relevant source code seems to be in TestForTransformation, but I'm honestly not sure if this is actually more of an issue with the Groovy AST transform api itself.

Environment Information

  • Operating System: macOS Sierra 10.12.1
  • Grails Version: 3.2.3
  • JDK Version: 1.8.0_101

Example Application

This bug report has three test classes (one for each kind of artefact). The tests pass if an exception is thrown when invoking the getter.
foo-bug-report-17122016.zip

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions