I have a problem trying to unit test a service in Grails (1.3.6).
The service has an instance of another service which it uses to create an object. I am trying to mock the creator service and also the object that it returns.
In the test class:
mockMyService = new MyService() // service under test
// Fake Asset object to 'create'
asset = mockFor(Asset)
asset.createMock()
// Mock the CreatorService and return the mocked asset
mockCreatorService = mockFor(CreatorService)
mockCreatorService.demand.generateAsset(){Section s, Date d, User u, AssetStatus a, String name -> return asset}
mockMyService = new MyService()
mockMyService.assetService = mockCreatorService.createMock()
From debugging and inspecting I’m fairly sure that the mock object is created ok and the service is mocked correctly and faking the generateAsset call.
In MyService, the call to the other (creator) service is:
Asset asset = creatorService.generateAsset(section, date, author, status, assetName)
I’m getting this error:
Cannot cast object ‘grails.test.GrailsMock@56c88357’ with class ‘grails.test.GrailsMock’ to class ‘com.xxxxxx.Asset
Which I think is due to the assigning of the mocked Asset in the call to generateAsset by MyService.
Can anyone shed light on this? If the reason is due to the assignment, is there a way around it? Or am I approaching this wrongly or have I missed something obvious.
It’s grails 1.3.6 (the port to Grails 2 won’t be complete for a while so stuck with this version this for a while).
Thanks.
Update:
OK so I’ve got around the cast exception by declaring the mocked objects like:
def testAssets = [
new Asset(id:123, name:......)]
mockDomain(Asset, testAssets)
But now it seems I have to declare all the non-null properties for the test Asset. This doesn’t seem right. For testing, I don’t care about the Asset at all, apart from the Id it has.
Your mocked
generateAsset()method needs to return notasset(themockFor(Asset)), but instead the value you got back from calling itscreateMock():