1
我正在嘗試爲Play 2.1.0的控制器方法編寫測試用例。該方法接收一個XML對象,做一些事情,並返回OK或依賴於XML BAD_REQUEST,有它的一部分:如何在Play中測試XML結果2.1.0
@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 --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();
}
});
}
這是我得到了什麼,當我跑「播放測試」:
...
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?