单元测试具有瞬态属性的域

时间:2012-09-04 22:12:20

标签: grails grails-2.0

我正在尝试对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
   }

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

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:1)

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

SecUser.springSecurityService = control

SecUser.metaClass.getSpringSecurityService = {-> control}

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