0

我如何在 Grails 域类中注入 springSecurityService 在单元测试控制器时,以下是示例代码,我不断收到错误 can not get encodePassword on null Object 和 getPrincipal();

 //Controller class
    class UserController{
     def save(){
         def user=new AppUser(params).save();
         render(user as JSON)  
      }
    }

    //Domain Class
    class User{
     transient springSecurityService
    String name
    String address
    String password
    String createdBy
    def beforeInsert(){
      password=springSecurityService.encodePassword(password);
      def principal = springSecurityService.getPrincipal() 
    }

//Controller Test
@TestMixin(GrailsUnitTestMixin)
@TestFor(UserController)
class UserControllerSpec {

   void setUp() {
   }
    void "test save"(){
     given:
     params.name="A"
     params.password="abc"
     params.address="XYZ" 
     when:
     controller.save();
     then:
     response.status=="200" 
    }

}
4

1 回答 1

0

Grails 2.x 支持使用'defineBeans' 闭包为测试环境定义spring bean。它支持控制器等中的依赖注入,我不确定它是否也适用于域对象。从理论上讲,它应该在域对象/控制器/服务之间保持一致

这篇文章可以帮助你

http://www.block-consult.com/blog/2011/08/17/inject-spring-security-service-into-domain-class-for-controller-unit-testing/

于 2015-10-31T17:17:38.283 回答