我之前写过另一个question。我在 Rest 服务上执行 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: A message body writer for Java type, class it.dni.rest.models.DeviceBean, and MIME media type, application/octet-stream, was not found at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:151)
所以,我的目标是直接映射 JSON 中的对象,反之亦然,但 Jersey 没有为我做这件事。我该怎么做才能在 Junit 测试中使用 Jersey 启用此映射?
最佳答案
很少有库能够真正帮助单元测试 REST Web 服务。放心:https://github.com/rest-assured/rest-assured是一个和 Unirest http://unirest.io/是另一个。我刚刚开始使用 Unirest,它对于 JSON 来说非常容易使用。可能值得一看。
关于java - 使用 JUnit 测试休息服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41472587/