【问题标题】:Grails 2.4.4: services does not inject: integration testGrails 2.4.4:服务不注入:集成测试
【发布时间】:2015-06-04 07:41:25
【问题描述】:

我有依赖服务的服务,例如:

class ParserService {
    def depService;

    private def parseLine(lineParts) {
    ...
    def set = depService.findItemByName(tmpModule.name);//depService == null
    ...

我尝试像这样实现集成测试:

@TestFor(ParserService)
class ParserServiceTest extends IntegrationSpec {
    def "should not parse comment"() {
        when:
        ...
        def resultList = service.parseAnnotations(inputStream);

resources.groovy:

beans = {
}

我有 NullPointerException: depService - null

【问题讨论】:

  • 你有一个叫DepService的服务吗?确保您的拼写正确
  • 我有 depService。我可以运行应用程序(不是测试) - 一切正常。
  • 也尝试发布更多代码,您如何调用服务(使用服务)

标签: grails integration-testing spock


【解决方案1】:

@TestFor 注释仅用于单元测试。集成测试像普通的 bean 一样工作,因此如果您将服务定义为类中的属性(例如在控制器/服务/域类中),Grails/Spring 将在测试中注入您的依赖项。

【讨论】:

    【解决方案2】:

    您的测试用例应该扩展GroovyTestCaseIntegrationSpec 类,仅此而已。当然,依赖注入会以通常的方式工作

    class ParserServiceTest extends IntegrationSpec {
       ParserService parserService
    
       def "should not parse comment"() {
        when:
        ...
        def resultList = parserService.parseAnnotations(inputStream)
    ...
    

    【讨论】:

      猜你喜欢
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 2017-03-08
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      相关资源
      最近更新 更多