【发布时间】:2009-07-13 22:38:33
【问题描述】:
今天我遇到了一个非常困难的 TDD 问题。我需要通过 HTTP POST 与服务器交互。我找到了 Apache Commons HttpClient,它可以满足我的需要。
但是,我最终得到了一堆来自 Apache Commons 的协作对象:
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 ala 依赖注入我感觉比较舒服,但是我对其他合作者怎么办?
我可以创建一堆工厂方法(或工厂类)来创建协作者,但我有点担心我会嘲笑太多。
跟进
感谢您的回答!我剩下的问题是这样的方法:
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 吗?
【问题讨论】:
标签: java unit-testing http tdd apache-commons