1

我正在尝试对 Spring Security Core Plugin 生成的用户域的控制器进行单元测试。控制器是使用 grails generate-all 生成的。该域有一个名为 springSecurityService 的瞬态属性。在我的单元测试中,我试图模拟该服务并将这个瞬态变量分配给我的模拟版本。但是,我收到此错误:

No such property: springSecurityService for class: com.myapp.security.SecUser Possible solutions:
springSecurityService groovy.lang.MissingPropertyException: No such property: springSecurityService for class: 
com.myapp.security.SecUser at com.myapp.security.SecUserControllerTests.setUp(SecUserControllerTests.groovy:26)

这是我的域的样子:

class SecUser {
    transient springSecurityService
    String username
    String password
    boolean enabled
    boolean accountExpired
    ....
    def beforeInsert() {
        encodePassword()
    }
    protected void encodePassword() {
        password = springSecurityService.encodePassword(password)
    }
}

这是我的测试的样子:

 package com.myapp.security

 import org.junit.*
 import grails.test.mixin.*
 import com.myapp.system.*
 import grails.plugins.springsecurity.*

 @TestFor(SecUserController)
 @Mock([SecUser,SpringSecurityService])
 class SecUserControllerTests {

    @Before void setUp() { 
       def service = mockFor(SpringSecurityService)
       service.demand.encodePassword(1..2) { a -> return 'd3jk3j4ls234'}
       def control = service.createMock()
       SecUser.springSecurityService = control
   }

不确定我做错了什么,甚至我什至可以用瞬态属性做这样的事情?

4

2 回答 2

2

可能是样机情况,看看这是否有效:

@Before void setUp() { 
    def service = mockFor(SpringSecurityService)
    // using the groovy MetaClass runtime
    service.metaclass.encodePassword = {def a -> 'd3jk3j4ls234'}
    SecUser.springSecurityService = service
}

或更静态的解决方案:

@Before void setUp() { 
    secUser.springSecurityService = [
        encodePassword : {def a -> 'd3jk3j4ls234'}
    ] as SpringSecurityService
}
于 2012-09-05T07:40:07.363 回答
1

您正在尝试将您的模拟分配给springSecurityService该类SecUser 就好像它是一个静态的),当它是一个实例变量时它将不起作用。我不是新 Grails 2 测试注释的专家,但我相信如果你更换

SecUser.springSecurityService = control

SecUser.metaClass.getSpringSecurityService = {-> control}

那么它应该做你想做的事。

于 2012-09-05T08:20:27.903 回答