我从Grails 3.3.8中的单元测试开始,我有ControllerSpec:
class FooControllerSpec extends Specification implements ControllerUnitTest<FooController> {
void "test index"() {
given:
controller.fooService = new FooServiceImplementation()
when:
controller.index()
then:
response.json
status == 200
}
void "test show"() {
given:
controller.fooService = new FooServiceImplementation()
when:
params['id'] = '000001400'
controller.show()
then:
status == 200
}
}
FooService是一个接口,没有实现。
@Service(Foo)
interface FooService {
Foo get(Serializable id)
List<Foo> list(Map args)
}
我像这样创建FooServiceImplementation:
class FooServiceImplementation implements FooService {
Foo get(Serializable id) {/*implementation here*/}
List<Foo> list(Map args) {/*implementation here*/}
}
这实际上有效,但是还有另一种形式可以在控制器中初始化服务?我想将FooService完全与将服务注入控制器时会编译的实现一起使用,以确保执行期间的结果与测试期间相同,因为我的FooServiceImplementation可以生成不同的结果,尽管我想您应该正确编写实现。
doWithSpring()
方法,该方法允许您将bean添加到此测试的上下文中。class FooControllerSpec extends Specification implements ControllerUnitTest<FooController> {
// Can use the same syntax here as can
// is used in grails-app/conf/spring/resources.groovy
Closure doWithSpring() {{ ->
// This bean will automatically be injected
// into the controller under test.
fooService FooService
}}
void "test index"() {
when:
controller.index()
then:
response.json
status == 200
}
void "test show"() {
when:
params['id'] = '000001400'
controller.show()
then:
status == 200
}
}