grails - unit testing
I have difficulty in making unit testing on the method contained in the domain like this:
This is the domain class
class UserRole implements Serializable {
User user
Role role
static void removeAll(User user) {
executeUpdate 'DELETE FROM UserRole WHERE user=:user', [user: user]
}
}
Then in the service :
class CorporateUserService {
def delete (def cifUserInstance) {
def userDetail,users,userRole
userDetail=UserDetails.findById(cifUserInstance.userDetails.id)
users=User.findById(userDetail.user.id)
userRole=UserRole.removeAll(users)
}
}
And in unit test:
void testDelete(){
def cifUserServi开发者_高级运维ce = new CorporateUserService()
mockDomain(UserRole,[])
def newuserRole2=UserRole.create(user,role2)
def newuserRole=UserRole.create(user,role)
newuserRole.executeUpdate 'DELETE FROM UserRole WHERE user= :user',[user: user]
try{
cifUserInstance = cifUserService.delete(cifUser)
}
catch(RuntimeException e){
println e
}
}
I have an error like this :
"groovy.lang.MissingMethodException: No signature of method: com.logika.corp.security.UserRole.executeUpdate() is applicable for argument types: (java.lang.String, java.util.LinkedHashMap) values: [DELETE FROM UserRole WHERE user= :user, [user:user1]]"
Can anyone know how to fix this error??
The problem here is that Grails adds a lot of dynamic methods at runtime. The mockDomain() method adds the dynamic findBy... methods etc, but it doesn't add the executeUpdate dynamic method.
So you have a couple of choices
1/ Move your unit test to the integration test folder. That way grails creates a full runtime environment and will add all the dynamic classes. (at the expense of a slower running time)
or
2/ Mock out the behaviour of the executeUpdate so that you are just testing your own code. (You don't necessarily want to unit test the grails code?) e.g.
registerMetaClass(UserRole )
UserRole.metaClass.static.executeUpdate={String query, Map items-> println "Mocking executeUpdate"}
try:
newuserRole.executeUpdate 'DELETE FROM UserRole WHERE user= :user',user
seen here
I hope it helps!
精彩评论