【发布时间】:2015-09-17 20:16:29
【问题描述】:
我已经在 bitbucket 上设置了一个测试应用程序来重现我的问题:
https://bitbucket.org/LuisMuniz/grails-bug-notacceptable
我有相当标准的 REST 控制器操作(保存),它返回 201(已创建)的 http 响应状态。
- 当我运行功能测试时,一切正常,http 状态为 201。
- 当我使用 grailsw 独立运行单元测试时,控制器按预期运行,返回代码 201。
- 当我在 Intellij IDEA 中运行相同的单元测试(尝试使用最新的 14.x 和最新的 15 EAP 版本)时,控制器返回 http 代码 406 (NOT_ACCEPTABLE)
我已经调试了测试执行,发现它涉及到 applicationContext 中的 mimeTypes,它只包含一个条目:text/html。
有人知道为什么会这样吗?这是一个已知问题吗?
有没有办法解决这个问题,或者我可以做些什么来使 Intellij 单元测试不会失败,或者如果它们在 Intellij 中执行,可以使用 Junit 规则跳过这些测试?
更新 根据需要,在此处发布代码。
package na
import grails.rest.RestfulController
import org.springframework.http.HttpStatus
class MyController extends RestfulController {
static responseFormats = ['json']
static allowedMethods = [save: "POST"]
def save() {
response.status=HttpStatus.CREATED.value()
respond request.JSON
}
}
功能测试(通过):
package na
import grails.util.Holders
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.springframework.context.ApplicationContext
import org.springframework.http.HttpStatus
import spock.lang.Specification
import wslite.rest.RESTClient
/**
* Created by lmuniz on 17/09/15.
*/
class MyControllerFuncSpec extends Specification {
def "Controller returns status 201"() {
given:
//noinspection GroovyAssignabilityCheck
def restClient = new RESTClient("http://localhost:8080/notacceptable")
when:
def response = restClient.post([path: "/my"]) {
json payload
}
then:
response.statusCode == HttpStatus.CREATED.value()
response.json == payload
where:
payload = [message: "Hello world"]
}
}
单元测试(在 IDEA 中失败):
package na
import grails.test.mixin.TestFor
import spock.lang.Specification
import spock.lang.Unroll
import static org.springframework.http.HttpStatus.CREATED
import static org.springframework.http.HttpStatus.NOT_ACCEPTABLE
/**
* See the API for {@link grails.test.mixin.web.ControllerUnitTestMixin} for usage instructions
*/
@TestFor(MyController)
class MyControllerSpec extends Specification {
boolean runsInIntellij() {
System.getProperty('idea.launcher.port') != null
}
@Unroll
def "Controller responds with http code #expectedResponseCode when it is running #inEnvironment"(){
given:
println System.getProperties().collect {it.toString()}.join('\n')
request.method = 'POST'
request.json = [message:"Hello world"]
when:
controller.save()
then:
response.status == expectedResponseCode
where:
expectedResponseCode = (runsInIntellij() ? NOT_ACCEPTABLE.value() : CREATED.value())
inEnvironment = (runsInIntellij() ? 'inside Intellij' : 'standalone')
}
}
【问题讨论】:
标签: rest unit-testing grails intellij-idea spock