【发布时间】:2016-03-04 17:33:18
【问题描述】:
在控制器的单元测试用例中,我只能注入在相应控制器中使用的服务。但是如果说控制器中的一个服务注入另一个服务,那么我的测试用例会失败,即无法在 null 上调用服务方法对象。
@TestFor(MyController)
@Mock(MyService)
class MyControllerSpec extends Specification {
void "test something"(){
when:
controller.method1();
then:
//something
}
}
class MyController(){
MyService myService
void method1(){
myService.serviceMethod()
}
}
class MyService(){
AnotherService anotherService
void serviceMethod(){
anotherService.anotherServiceMethod()
}
}
class AnotherService(){
void anotherServiceMethod(){
\\something
}
}
在这种情况下,我得到 无法在空对象上调用“anotherServiceMethod”。 有什么方法可以测试这种类型的控制器吗?在另一个服务中注入服务是一种好方法吗?
【问题讨论】:
标签: unit-testing grails grails-3.0.10