【发布时间】:2017-01-04 20:21:05
【问题描述】:
我之前写过另一个question。在那里我在休息服务上执行 JUnit 测试时出错,因为 JSON 只是 Jersey 的字符串。
public class MachineResponseTest {
private static final String BASE_URI = "http://localhost:8080/dni-fe/home"
@Test
public void testDevice() {
WebResource resource = Client.create().resource(BASE_URI);
resource.accept(MediaType.APPLICATION_JSON);
StringBuilder sb = new StringBuilder();
sb.append("{\"name\":\"123456\",\n");
sb.append(" \"country\":\"Spain\",\n");
sb.append(" \"company\":\"xxx\",\n");
sb.append(" \"model\":\"1.10.0\"\n}");
MachineResponse result = resource.post(MachineResponse.class,sb.toString());
}
然后我尝试将 StringBuilder 转换为 org.codehaus.jettison.json.JSONObject 对象并返回一个插入 POJO 的字符串;这样之前的错误就消失了:
try{
StringBuilder sb = new StringBuilder();
sb.append("{\"name\":\"123456\",\n");
sb.append(" \"country\":\"Spain\",\n");
sb.append(" \"company\":\"xxx\",\n");
sb.append(" \"model\":\"1.10.0\"\n}");
JSONObject jsonObj = new JSONObject(sb.toString());
}
catch(JSONException e){
....
}
String result = resource.post(String.class,jsonObj);
例如,假设我有这个 POJO 类:
public class ItemBean implements Serializable {
private static final long serialVersionUID = 7438046484680798158L;
private String name;
private String country;
private String company;
private String model;
public ItemBean() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
我尝试使用这个 POJO 来构建我的测试,例如:
ItemBean item = new ItemBean();
item.setName("123456");
item.setCountry("Spain");
item.setCompany("xxxx");
item.setModel("1.10.0");
String result = resource.post(String.class,item);
但测试以错误结束:
com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException:消息体 Java 类型、it.dni.rest.models.DeviceBean 类和 MIME 的编写器 媒体类型 application/octet-stream 未在 com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:151)
所以,我的目标是直接在 JSON 中映射一个对象,反之亦然,但 Jersey 并没有为我做这件事。我可以做些什么来在 Junit 测试中使用 Jersey 启用此映射?
【问题讨论】:
-
你的例子没有多大意义:你在最后一个代码示例中引用的
resource仅在测试类的方法testDevice中实例化,实际上并没有断言或验证任何事物?请将您的问题修改为minimal complete and verifiable example。 -
好的,但是如果我的测试出错,我什么也做不了。