我正在尝试为Play 2.1.0的控制器方法编写一个测试用例。该方法接收一个XML对象,执行一些操作,然后根据XML返回OK或BAD_REQUEST,这是其中的一部分:
@BodyParser.Of(BodyParser.Xml.class)
public static Result save() {
Document dom = request().body().asXml();
System.out.println(request().body());
if (dom == null) {
return badRequest(error.render("Se esperaba Xml"));
} else {
...当我尝试用curl测试它时,它工作得很好:
$ curl --header "Content-type: text/xml" --request POST --data '<gloo>Guillaume</gloo>' -verbose http://localhost:9000/api/xml/
* About to connect() to localhost port 9000 (#0)
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9000 (#0)
> POST /api/xml/ HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:9000
> Accept: */*
> Referer: rbose
> Content-type: text/xml
> Content-Length: 22
>
* upload completely sent off: 22 out of 22 bytes
< HTTP/1.1 200 OK
< Content-Type: text/xml; charset=utf-8
< Content-Length: 89
<
* Connection #0 to host localhost left intact
<?xml version="1.0" encoding="utf-8"?><gloo>dd8d191c-8a27-4dad-a624-1c5a6a5d9d03</gloo>但是,当我尝试测试时,它看起来像是向控制器传递了一个错误的XML。这是我的测试用例:
@Test
public void saveActionRespondsOkOnValidContent() {
running(fakeApplication(), new Runnable() {
public void run() {
Result result = route(fakeRequest(POST, "/api/xml/")
.withHeader(CONTENT_TYPE, "text/xml").withTextBody(
"<gloo>Probando el API xml</gloo>"));
System.out.println(contentAsString(result));
assertThat(status(result)).isEqualTo(OK);
assertThat(contentType(result)).isEqualTo("text/xml");
assertThat(contentAsString(result)).isNotEmpty();
}
});
}这是我在运行"play test“时得到的结果:
...
DefaultRequestBody(None,None,None,None,None,None,true)
<?xml version="1.0" encoding="utf-8"?><gloo>Se esperaba Xml</gloo>
[error] Test api.XmlApiTests.saveActionRespondsOkOnValidContent failed: expected:<[2]00> but was:<[4]00>
...第一行由控制器跟踪,表示没有XML。第二个由测试用例跟踪,表示接收到的错误消息。第三个问题是我的测试用例失败:我在等待OK的时候收到了一个BAD_REQUEST。
因此,我的问题(最后)是:如何编写一个测试用例,将有效的XML发送到我的方法?
发布于 2013-12-21 07:12:34
在FakeRequest中似乎有一个方法withXmlBody,就像文档中的here一样。使用这种方法而不是withTextBody应该会有所帮助。
可以尝试的另一件事(我自己还没有测试过)是将Content-Type更改为application/xml
https://stackoverflow.com/questions/20713264
复制相似问题