Cap*_*ain 10 grails unit-testing
我需要一些奇怪的问题,我正面临单元测试一个非常基本的Grails 2.4.1控制器.
鉴于此控制器:
class AuthenticationEventController {
def index() {
// Sorry, ajax only!
if(!request.xhr) {
redirect(controller: "main")
return false
}
render(template: "index")
return
}
}
Run Code Online (Sandbox Code Playgroud)
而这个测试:
@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'
}
}
Run Code Online (Sandbox Code Playgroud)
我在"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)
Run Code Online (Sandbox Code Playgroud)
小智 26
最有可能的问题是你正在使用
import grails.transaction.Transactional
Run Code Online (Sandbox Code Playgroud)
代替
import org.springframework.transaction.annotation.Transactional
Run Code Online (Sandbox Code Playgroud)
对于@Transactionalgroovy类中的注释.
为什么,没有明确的答案,主要的区别或为什么测试不能很好地解决这个问题.此外,通常只有在您测试一个后面还有2个类层的类时才会发生这种情况.
以下内容适用于 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")
}
}
}
Run Code Online (Sandbox Code Playgroud)
单元测试:
// 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'
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助。
| 归档时间: |
|
| 查看次数: |
2657 次 |
| 最近记录: |