简体   繁体   English

grails - 单元测试

[英]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

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]]" “groovy.lang.MissingMethodException:无方法签名:com.logika.corp.security.UserRole.executeUpdate() 适用于参数类型:(java.lang.String, java.util.LinkedRHashMap) 值:[DELETE FROM UserRoleMap] WHERE 用户 =:用户,[用户:用户 1]]"

Can anyone know how to fix this error??谁能知道如何解决这个错误??

The problem here is that Grails adds a lot of dynamic methods at runtime.这里的问题是Grails在运行时添加了很多动态方法。 The mockDomain() method adds the dynamic findBy... methods etc, but it doesn't add the executeUpdate dynamic method. mockDomain() 方法添加了动态 findBy... 方法等,但没有添加 executeUpdate 动态方法。

So you have a couple of choices所以你有几个选择

1/ Move your unit test to the integration test folder. 1/ 将您的单元测试移动到集成测试文件夹。 That way grails creates a full runtime environment and will add all the dynamic classes.这样 grails 将创建一个完整的运行时环境并将添加所有动态类。 (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. 2/ 模拟 executeUpdate 的行为,以便您只是测试自己的代码。 (You don't necessarily want to unit test the grails code?) eg (您不一定要对 grails 代码进行单元测试?)例如

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!我希望它有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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