如何在Grails中测试注入其他服务的服务?

时间:2015-05-26 17:45:00

标签: grails spock

从其他服务调用服务时出错。

| Running 13 unit tests... 1 of 13
| Failure:  test myAction(MyServiceSpec)
2015.05.27/02:17:09  ERROR StackTrace -- Full Stack Trace:
java.lang.NullPointerException: Cannot invoke method saveUserRole() on null object

我做了两项服务如下。

class MyService {
    def userRoleService
    def myAction(){
        def userQuery = User.where{username == "test1"}.get()
        def roleQuery = Role.where{authority == "ROLE_ADMIN"}.get()
        if (userQuery && roleQuery){
            userRoleService.saveUserRole(userQuery, roleQuery)
        }
    }
}

class UserRoleService{
    def saveUserRole(user, role){
        new UserRole(role: role, user:user).save(flush: true)
    }
}

我想测试myAction()的{​​{1}},所以我提出了MyService,如下所示。

MyServiceSpec

调用@TestFor(DatabaseService) @TestMixin(DomainClassUnitTestMixin) class MyServiceSpec extends Specification { def userRoleService def setup() { } def cleanup() { } void "test myAction"(){ setup: mockDomain( Role,[ [authority:"ROLE_ADMIN"], [authority:"ROLE_USER"] ] ) mockDomain( User,[ [username:"test1",password:"1234"] ] ) mockDomain( UserRole ) when: "call the action" service.myAction() then: UserRole.count() == 1 } } 时会导致此错误。

如何在没有错误的情况下测试userRoleService.saveUserRole(userQuery, roleQuery) myAction()

----

更新

我更改了Spec Class,如下所示。

MyService

测试认可服务类,谢谢。

但似乎这个测试用例不好或者这个程序设计不好。

您是否有任何关于引用此代码的建议?

1 个答案:

答案 0 :(得分:1)

在评论之后,我更改了Spec Class,如下所示。

@TestFor(DatabaseService)
@TestMixin(DomainClassUnitTestMixin)
class MyServiceSpec extends Specification {
    def setup() { }
    def cleanup() { }
    void "test myAction"(){
        setup:
        mockDomain( Role,[ [authority:"ROLE_ADMIN"], [authority:"ROLE_USER"] ] )
        mockDomain( User,[ [username:"test1",password:"1234"] ] )
        mockDomain( UserRole )
        def userQuery = User.where{username == "test1"}.get()
        def roleQuery = Role.where{authority == "ROLE_ADMIN"}.get()
        def mockUserRoleService = Mock(UserRoleService){
            1 * saveUserRole(userQuery, roleQuery) >> new UserRole(role: roleQuery, user:userQuery).save(flush: true)
        }
        service.userRoleService = mockUserRoleService

        when: "call the action"
        service.myAction()

        then:
        UserRole.count() == 1
    }   
}

测试认可服务类,谢谢。

但似乎这个测试用例不好或者这个程序设计不好。

您是否有任何关于引用此代码的建议?

相关问题