如何将SpringSecurityService注入到Grails 2.4.2中的控制器单元测试的Grails域类中

时间:2015-10-31 16:35:28

标签: unit-testing grails spring-security grails-domain-class grails-2.4

如何在Grails Domain类中注入springSecurityService在单元测试Controller时,下面是示例代码,我不断得到错误,无法在null对象上获取encodePassword,类似于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" 
    }

}

1 个答案:

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