Was writing unit test cases and at one point I needed to do some meta programming to test a method as below.
void "test method:resolver"(){
setup:"mocked resolver"
ContextHolder.getMetaClass().static.getBean = {
Resolver resolver = Mock(Resolver)
resolver(_) >> {HttpServletRequest request1->
return 1;
}
}
and:"mocked getAppName"
CoreUtil.metaClass.static.getAppName = {
return "$apiName"
}
when:
UserGroupRole userGroupRole = service.resolve(username)
then:
userGroupRole != null
where:
apiName || username
"core-blog" || "test11"
}
Following are the scenarios that I have gone through for running test cases:
- When running test case individually, It works perfectly.
- When running test case as a whole Specification i.e. run the Specification class itself, It works perfectly
- But when running the test cases as whole by
grails test-app :unit
It fails saying Class.metaclass.static say can not get static on null
Please help!
If you're making metaclass changes in your tests, you need to clean up those metaclass changes in a cleanup step at the end of each test. Otherwise you risk test pollution.