我在我的java項目中使用RESTful應用程序。通常,在我的單元測試類,我用這樣的方法:通用方法,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()方法兩次......如果我用它只有一次...它的工作原理...該死的
從瀏覽器調用工作正常,寧靜的方法都可以。但是我需要單元測試,當我按照正常的方式進行操作時(如第一個代碼示例),但在嘗試clientResponse.getEntity(clazz)時不起作用;我認爲有泛型類型的問題... –