简体   繁体   English

NPE在单元测试中用于grails服务

[英]NPE in grails service within unit test

I have a very weird error, hope you can help me! 我有一个很奇怪的错误,希望您能帮助我! I'm currently using grails 2.5.1. 我当前正在使用grails 2.5.1。

My service is something like this: 我的服务是这样的:

@Transactional
abstract class MyParentService {
    AnotherService anotherService
    [...]
    @Transactional(readOnly = true)
    List<Project> allProjects(){
        anotherService.doStuff()
    }
    [...]
}

Same result if service is not abstract. 如果服务不是抽象的,则结果相同。 Then, I have another service that extends that one: 然后,我有另一项服务扩展了该服务:

@Transactional
class MyChildService extends MyParentService {
    def aMethod(){
       List<Projects> projects = allProjects()
       [...]
    }
}

Then I have a spock unit test: 然后我有一个spock单元测试:

@TestFor(MyChildService)
class MyChildServiceSpec extends Specification {
  AnotherService anotherService 
  def setup(){
    anotherService = Mock()
    service.anotherService = anotherService
    List<Project> list = [new Project(a: 1), new Project(a:2)]
    anotherService.doStuff() >> list
  }

  void "do some stuff"(){
    when:
    aMethod()

    then:
    //some asserts
  }
}

When I run the tests, I get an NPE error in this line: 运行测试时,此行出现NPE错误:

List<Projects> projects = allProjects()

The method allProjects is never called (i added some traces and never are shown). 永远不会调用allProjects方法(我添加了一些跟踪信息,并且从不显示)。

The weird thing is that if I comment "= allProjects()" out, execute the test (of course, it fails because of asserts), remove the comment again and execute test again, it passes. 奇怪的是,如果我注释掉“ = allProjects()”,执行测试(当然,由于断言而失败),再次删除注释并再次执行测试,它就通过了。 But later on, it will fail again for same NPE reason. 但是稍后,由于相同的NPE原因,它将再次失败。

I haven't got the error when executing the code using the application, so it's only a unit test thing 使用应用程序执行代码时我没有出现错误,因此这只是单元测试

I should say that I have more than one service extending MyParentService and have the same problem with all unit tests 我应该说,我有一个以上的服务扩展了MyParentService,并且所有单元测试都存在相同的问题

Any ideas? 有任何想法吗?

I answer my question just in case other people come here with the same problem. 我回答我的问题是为了防止其他人也遇到同样的问题。 I haven't found the problem, but fixed it just changing MyParentService to be a trait and children implement it instead of extending. 我没有发现问题,但仅通过将MyParentService更改为特征并由子代实现而不是扩展来解决。 Error seems to not happening again 错误似乎不再发生

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM