今天我遇到了非常困難的TDD問題。我需要通過HTTP POSTs與服務器交互。我找到了Apache Commons HttpClient,它可以滿足我的需求。與多個合作伙伴進行單元測試
然而,我結束了從Apache的百科全書一堆協作對象的:
public void postMessage(String url, String message) throws Exception {
PostMethod post = new PostMethod(url);
RequestEntity entity = new StringRequestEntity(message,
"text/xml; charset=ISO-8859-1");
post.setRequestEntity(entity);
HttpClient httpclient = new HttpClient();
try {
int result = httpclient.executeMethod(post);
System.out.println("Response status code: " + result);
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
} finally {
post.releaseConnection();
}
}
我有一個PostMethod
對象,RequestEntity
對象和HttpClient
對象。我覺得在依賴注入方面通過HttpClient
相對比較舒服,但是我對其他合作者做了什麼?
我可以創建一堆工廠方法(或工廠類)創建的合作者,但我有點害怕,我會嘲笑太多。
跟進
感謝您的答案!我剩下的問題是這樣的方法:
public String postMessage(String url, String message) throws Exception {
PostMethod post = new PostMethod(url);
RequestEntity entity = new StringRequestEntity(message,
"text/xml; charset=ISO-8859-1");
post.setRequestEntity(entity);
HttpClient httpclient = new HttpClient();
httpclient.executeMethod(post);
return post.getResponseBodyAsString();
}
如何正確地驗證返回值是post.getResponseBodyAsString()
?我需要模擬post
以及client
嗎?