【发布时间】:2014-08-28 14:57:32
【问题描述】:
我需要一些帮助来解决我在对一个非常基本的 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)
【问题讨论】:
-
您的测试在 grails 2.3.8 中通过(我还没有 2.4.1),所以也许它是 grails 缓存的东西 - 如果您还没有尝试过 grails clean 的话?否则,可能值得看看 Grails 2.4 中的变化
-
为了让它在 2.4.1 中工作,我必须在测试中添加一个空的 def setup(){} 和 def cleanup() {} 方法,否则我得到方法未找到错误,也许你值得一试吗?
-
2.4.0 和 2.4.1 都有一些严重的问题,这些问题在 2.4.2 中得到了解决。我没有机会尝试您的测试,但如果可能,我会考虑迁移到 2.4.2。
-
你不应该需要一个空的
setup()或cleanup()方法,你不应该升级到2.4.2 来测试它。 github.com/jeffbrown/xhrtest 的项目包含我粘贴到下面答案中的代码,并且该测试似乎有效。
标签: unit-testing grails