简体   繁体   中英

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 cifUserService = 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?) eg

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM