嗨,我有一个名为 ApiController 的 Controller ,它使用名为 ApiService 的服务,如下所示:
def createCategory(){
def jsonObj = request.JSON
jsonObj.each{ key, value ->
params.put(key,value)
}
render apiService.createCategory(params)
}
哪个工作正常。
但我似乎无法为它编写测试。
这是我有多远:
@TestFor(ApiController)
@Mock([Category,ApiService])
class CategorySpec extends Specification {
def setup() {
}
def cleanup() {
}
void "test"() {
setup:
def apiService = Mock(ApiService)
when:
request.method = 'POST'
request.requestMethod = 'POST'
params.categoryID = 'test'
controller.createCategory()
then:
println(response)
1==1
}
由此我得到以下错误:
java.lang.NullPointerException: Cannot invoke method createCategory() on null object
这显然是因为它看不到我的 apiService bean。所以我的问题是我如何在 Spock 中做到这一点?
最佳答案
它最有可能与 Transactional bug
有关:https://github.com/grails/grails-core/issues/1501
ApiService apiService = new ApiService()
controller.apiService = apiService
apiService.transactionManager = Mock(PlatformTransactionManager) { getTransaction(_) >> Mock(TransactionStatus) }
这是一个临时修复(根据错误报告评论)......这对我有用:)
关于unit-testing - Grails Spock 测试 Controller 和服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26862914/