最近发现了一个奇怪的场景,即服务中的服务依赖注入,在运行 test-app
时抛出NPE服务中注入的原因是使GORM / criteriaBuilder尽可能干。以下是我的两项服务。
实施了 SearchService1.groovy 课程,以提供搜索功能。
class SearchService1{
def search = { ...//Calls to local closures to build a dynamic criteria }
...
}
Class SearchService2.groovy 使用 SearchService1 类的搜索关闭
class SearchService2{
def searchService1
...
def searchEntity(){
searchService1.search()
}
}
现在,上述代码在 run-app 模式下运行良好。 但是对于为SearchService2编写的Integration测试会抛出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
...
}
}
答案 0 :(得分:1)
对于TestClass,将searchService1注入searchService2对象,如下所示:
def searchService2
def searchService2.searchService1 = new SearchService1()
但是来吧!这是正确的方法吗?任何人都可以解释上面的错误,这就是为什么在运行test-app时没有实例化Service-in-Service。
答案 1 :(得分:0)
试试这个:
class SearchService2Tests extends GroovyTestCase {
...
def searchService1
def searchService2
...
void testWhenSearch(){
def resultSet = searchService2.searchEntity()
...
}
}
但使用标准Grails服务命名约定和展示位置