我在bitbucket上设置了一个测试应用程序,可以重现我的问题:
https://bitbucket.org/LuisMuniz/grails-bug-notacceptable
我有相当标准的REST控制器操作(保存),它返回http响应状态201(CREATED)。
我已经调试了测试执行,并发现它涉及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')
}
}
答案 0 :(得分:0)
在您的控制器中,而不是
回复request.JSON
你可以试试这个:
render(status:response.status)