我正在嘗試編寫一個簡單的測試類來模擬通過POST
方法創建客戶的RESTful Web服務。以下失敗爲assertEquals
,我收到400 Bad Request
響應。我無法使用調試器來觀察堆棧跟蹤。但控制檯告訴我以下...如何使用JerseyTest框架發送/接受JSON
信息:已啓動的監聽器綁定到[localhost:9998]
信息:[HttpServer]已啓動。
public class SimpleTest extends JerseyTestNg.ContainerPerMethodTest {
public class Customer {
public Customer() {}
public Customer(String name, int id) {
this.name = name;
this.id = id;
}
@JsonProperty("name")
private String name;
@JsonProperty("id")
private int id;
}
@Override
protected Application configure() {
return new ResourceConfig(MyService.class);
}
@Path("hello")
public static class MyService {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public final Response createCustomer(Customer customer) {
System.out.println("Customer data: " + customer.toString());
return Response.ok("customer created").build();
}
}
@Test
private void test() {
String json = "{" +
"\"name\": \"bill\", " +
"\"id\": 4" +
"}";
final Response response = target("hello").request(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(json));
System.out.println(response.toString());
assertEquals(response.getStatus(), 200);
}
}
你是一個了不起的人。你剛剛解決了一個讓我超過6個小時的問題。謝謝 –
@JasonJavier順便說一下,感謝您的[MCVE](http://stackoverflow.com/help/mcve)。這就是我如何鼓勵澤西島相關的問題。我們可以複製並粘貼到單個課程中進行測試。即使問題與測試框架無關,將所有功能集成到一個可運行測試中也有助於更快地找出問題。它還有助於OP縮小問題範圍,使調試更加集中。 –