我在我的 java 项目中使用 RESTful 应用程序。通常在我的单元测试类中,我使用这样的方法:
public Employee getEmployeeByEmail(String email) {
ClientResponse clientResponse = webResource.path(beginPath + "getByEmail/" + email).get(
ClientResponse.class);
Employee employee = null;
if (200 == clientResponse.getStatus()) {
employee = clientResponse.getEntity(Employee.class);
}
return employee;
}
...但我必须在几乎 12 个不同的类中使用类似的方法。这就是我决定做的事情:
public class TestManager<T> {
private WebResource webResource;
private String beginPath;
private Class<T> clazz;
public TestManager(WebResource webResource, String beginPath, Class<T> clazz) {
this.webResource = webResource;
this.beginPath = beginPath;
this.clazz = clazz;
}
public boolean objectExists(String methodPath, String uniqueFieldName, String uniqueField) {
boolean check = false;
ClientResponse clientResponse = webResource.path(beginPath + methodPath + "/" + uniqueField).get(
ClientResponse.class);
JSONObject jsonObject = clientResponse.getEntity(JSONObject.class);
if (200 == clientResponse.getStatus() && !jsonObject.isNull(uniqueFieldName)) {
check = true;
}
return check;
}
public T getObjectById(String methodPath, long id) {
ClientResponse clientResponse = webResource.path(beginPath + methodPath + "/" + id).get(
ClientResponse.class);
T object = null;
if (200 == clientResponse.getStatus() && !clientResponse.getEntity(JSONObject.class).isNull("id")) {
object = clientResponse.getEntity(clazz);
}
return object;
}
}
方法 objectExists() 工作正常,但 getObjectById() 方法生成堆栈跟踪:
javax.ws.rs.WebApplicationException: javax.xml.bind.UnmarshalException: Error creating JSON-based XMLStreamReader - with linked exception:[javax.xml.stream.XMLStreamException: java.io.IOException: stream is closed]
看来我不能这样做:
object = clientResponse.getEntity(clazz);
但我不知道如何解决它。对不起我的英语:P
编辑:我使用球衣
Edit2: 解决方案:问题是我两次使用 getEntity() 方法......如果我只使用一次......它可以工作......该死