Reputation: 2931
I have a domain object hierarchy with a top level abstract class. In GORM, they could be defined like this:
abstract class Dog {
...
}
class Collie extends Dog {
...
}
Now I would like to unit test a controller which gets passed a Dog ID, like so:
//in the unit test
new Collie(id:1).save(validate:false)
params.id = 1
controller.show()
and
//in the tested controller
def dog = Dog.get(params.id)
This works with real GORM, unfortunately nothing gets returned by the testing GORM implementation as I cannot use @Mock(Dog)
or mockDomain(Dog)
(doing so returns an exception as Dog is abstract) and @Mock(Collie)
is not enough (even though the actual mocked object is in fact a Collie instance).
Any hints?
Upvotes: 1
Views: 688
Reputation: 2931
So one solution I came up with that worked was using meta programming:
Dog.metaClass.static.get = { Long id ->
return Collie.get(id)
}
This isn't the most obvious way and it could get complicated where you actually use more than one subclass in your unit tests, so if someone knows how to do it properly, please contribute.
Upvotes: 3