[英]Nullpointer in simple grails controller unit test
我需要一些奇怪的問題,我正面臨單元測試一個非常基本的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)
最有可能的問題是你正在使用
import grails.transaction.Transactional
代替
import org.springframework.transaction.annotation.Transactional
對於groovy類中的@Transactional
注釋。
為什么,沒有明確的答案,主要的區別或為什么測試不能很好地解決這個問題。 此外,通常只有在您測試一個后面還有2個類層的類時才會發生這種情況。
您是否在代碼中的任何其他位置使用域類? 我遇到了同樣的問題(由TransactionTemplate引發的NPE #exend),解決方案是將@Mock用於我的一個實體,根據這個jira問題: https : //jira.grails.org/browse/GRAILS-11045
以下內容適用於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'
}
}
我希望有所幫助。
在嘗試Spy Transactional服務時,我得到了相同的堆棧跟蹤。
我找到了幫助我的解決方案。 所以我只是在spied服務中初始化transactionManager。
見例子:
SomeTransactionalService sts = Spy(SomeTransactionalService)
sts.transactionManager = transactionManager // so you need to add init transactionManager
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.