最近遇到了一个奇怪的场景,服务中的服务的依赖注入,在运行test-app时抛出 NPE
service-in-service 注入的原因是使 GORM/criteriaBuilder 尽可能 DRY。以下是我的两项服务。
实现了以下类SearchService1.groovy以提供搜索功能。
class SearchService1{
def search = { ...//Calls to local closures to build a dynamic criteria }
...
}
SearchService2.groovy类使用SearchService1类的搜索闭包
class SearchService2{
def searchService1
...
def searchEntity(){
searchService1.search()
}
}
现在,上述代码在运行应用程序模式下运行良好。但是对于为 SearchService2 编写的集成测试,会抛出 NPE,如下所示:
Cannot invoke method searchEntity() on null object
java.lang.NullPointerException: Cannot invoke method search() on null object
at com.myapp.service.SearchService2.searchEntity(SearchService2.groovy:326)
at com.myapp.service.SearchService2$searchEntity$0.callCurrent(Unknown Source)
at com.myapp.service.SearchService2.searchEntity(SearchService2.groovy:295)
at com.myapp.service.SearchService2$searchEntity.call(Unknown Source)
at com.myapp.integration.SearchService2Tests.testWhenSearch(SearchService2Tests.groovy:125)
我在这里错过了一些非常基本的东西吗?任何想法都非常感谢。许多Thnx :)
来自 TestClass 的片段:
class SearchService2Tests extends GroovyTestCase{
...
def searchService2
...
void testWhenSearch(){
def resultSet = searchService2.searchEntity() //This is the line throwing NPE
...
}
}