【问题标题】:Inject Spring Beans from resources.groovy into integration test for a Grails 3 Service将 resources.groovy 中的 Spring Bean 注入 Grails 3 服务的集成测试中
【发布时间】:2016-12-03 12:58:11
【问题描述】:

我正在尝试为注入了 spring bean 的服务编写集成测试。 spring bean 在resources.groovy 中定义。我的服务正在使用的 bean 似乎没有在我的集成测试中被注入,但是当我运行 grails run-app 时它被很好地注入。

这是一个最小的失败示例:

grails-app/conf/spring/resources.groovy

beans = {
  myBean(Object){}
}

grails-app/services/MyService.groovy

class MyService {
  def myBean

  def serviceMethod(){
    myBean.class.simpleName
  }
}

grails-app/src/integration-test/groovy/MyServiceSpec.groovy

@Integration
class MyServiceSpec extends Specification {
  def myService

  when:
  def myBean = myService.myBean

  then:
  myBean != null
}

Grails 版本信息:

$ grails -v
| Grails Version: 3.1.9 
| Groovy Version: 2.4.7
| JVM Version: 1.8.0_92

更新:

Spring 似乎可以很好地注入其他服务。如果我在MyService 中声明另一个服务,它就会被注入。

class MyService {
  def myBean
  def myOtherService

  def serviceMethod(){
    myBean.class.simpleName
  }
}

【问题讨论】:

  • 集成不应像您所拥有的那样。添加一个测试用例,然后使用whenthen
  • 你是什么意思“集成不应该像你所拥有的那样”。我的测试用例确实有 when 和 then...
  • 你好。这个问题有运气吗?您是否找到了使其工作的任何方法或解决方法?

标签: grails spock


【解决方案1】:

我可能迟到了这个派对...但是,对于未来的读者,请尝试在您的 application.yml 中将 grails.gorm.autowire 设置为 true

【讨论】:

    【解决方案2】:

    您的示例有许多特殊之处,例如

    beans = {
      myBean(Object){}
    }
    

    我无法想象您为什么要创建 Object 类型的 bean,但也许这是您为示例目的所做的简化,而真正的 bean 具有不同的类型。

    @Integration
    class MyServiceSpec extends Specification {
      def myService
    
      when:
      def myBean = myService.myBean
    
      then:
      myBean != null
    }
    

    这个测试归结为测试依赖注入是否有效,这意味着您测试的是 Spring/Grails 而不是您自己的代码。这不是你应该测试 IMO 的东西。

    无论如何要解决您的问题,我认为您只需要添加一个@Autowired 注释

    import org.springframework.beans.factory.annotation.*
    
    @Integration
    class MyServiceSpec extends Specification {
    
      @Autowired
      def myService
    
      when:
      def myBean = myService.myBean
    
      then:
      myBean != null
    }
    

    【讨论】:

    • 你好。该示例的重点是表明依赖注入不起作用:)。该测试只是演示问题的人为示例。不幸的是,添加 @Autowired 并没有任何区别。服务没有被注入,myBean 仍然为空。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    相关资源
    最近更新 更多