我需要一些奇怪的问题帮助,我正面临着测试一个非常基本的Grails 2.4.1控制器的问题。
鉴于此控制器:
class AuthenticationEventController {
def index() {
// Sorry, ajax only!
if(!request.xhr) {
redirect(controller: "main")
return false
}
render(template: "index")
return
}
}
这个测试:
@TestFor(AuthenticationEventController)
class AuthenticationEventControllerSpec extends Specification {
void "Test that the index rejects non-ajax calls"() {
given:
request.isXhr = { false }
when:
controller.index()
then:
response.redirectedUrl == '/main'
}
}
我在“controller.index()”调用中得到NullPointerException。
java.lang.NullPointerException
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130)
at org.codehaus.groovy.grails.orm.support.GrailsTransactionTemplate.execute(GrailsTransactionTemplate.groovy:85)
at au.com.intrinsicminds.advansys.controller.AuthenticationEventControllerSpec.Test that the index rejects non-ajax calls(AuthenticationEventControllerSpec.groovy:17)
答案 0 :(得分:25)
最有可能的问题是你正在使用
import grails.transaction.Transactional
而不是
import org.springframework.transaction.annotation.Transactional
用于groovy类中的@Transactional
注释。
为什么,没有明确的答案,主要区别或为什么测试不能很好地解决这个问题。 此外,通常只有在您测试一个后面还有2个类层的类时才会发生这种情况。
答案 1 :(得分:4)
您是否在代码中的任何其他位置使用域类?我遇到了同样的问题(由TransactionTemplate引发的NPE #exend),解决方法是将@Mock用于我的一个实体,根据这个jira问题:https://jira.grails.org/browse/GRAILS-11045
答案 2 :(得分:0)
以下内容适用于Grails 2.4.1。
控制器:
// grails-app/controllers/demo/AuthenticationEventController.groovy
package demo
class AuthenticationEventController {
def index() {
if(!request.xhr) {
redirect(controller: "main")
} else {
render(template: "index")
}
}
}
单元测试:
// test/unit/demo/AuthenticationEventControllerSpec.groovy
package demo
import grails.test.mixin.TestFor
import spock.lang.Specification
@TestFor(AuthenticationEventController)
class AuthenticationEventControllerSpec extends Specification {
void "Test that the index redirects for non-ajax calls"() {
when:
controller.index()
then:
response.redirectedUrl == '/main'
}
void "Test that index renders template for ajax calls"() {
given:
request.makeAjaxRequest()
views['/authenticationEvent/_index.gsp'] = 'my template text'
when:
controller.index()
then:
response.contentAsString == 'my template text'
}
}
我希望有所帮助。
答案 3 :(得分:0)
当尝试间谍交易服务时,我得到了相同的堆栈跟踪。
我找到了对我有帮助的解决方案。所以我只是在间谍服务中初始化transactionManager。
查看示例:
SomeTransactionalService sts = Spy(SomeTransactionalService)
sts.transactionManager = transactionManager // so you need to add init transactionManager