Re: [問題] 與網路狀態相關的Test Case該怎麼寫
※ 引述《MIDlet (遙遙無期)》之銘言:
: 小弟正在學習寫Test Case
: 本來寫得很開心
: 結果卡關了
: 有個method內容類似下面的程式碼
: public String connect(String userId) {
: HttpClient client = new DefaultHttpClient();
: HttpGet get = new HttpGet(url + "?userId=" + userId);
: ResponseHandler<String> handler = new BasicResponseHandler();
: try {
: String responseBody = client.execute(get, handler);
: return "0000";
: } catch (Exception e) {
: return "1000";
: } finally {
: client.getConnectionManager().shutdown();
: }
: }
: 一般method傳入參數然後檢查回傳值我知道怎麼寫
: 但像這種method
: 回傳值會取決於網路連線成不成功
: 該如何寫Test Case並進行測試呢?
簡單的就自己換掉 result
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
public class MyHttpClient {
public String connect(String url, String userId) {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url + "?userId=" + userId);
ResponseHandler<String> handler = new BasicResponseHandler();
try {
String responseBody = client.execute(get, handler);
return "0000";
} catch (Exception e) {
return "1000";
} finally {
client.getConnectionManager().shutdown();
}
}
}
==============================================================
import static org.junit.Assert.*;
import org.junit.Test;
public class MyHttpClientTest {
@Test
public void testOkCase() {
// arrange mock
MyHttpClient okResultClient = new MyHttpClient() {
@Override
public String connect(String url, String userId) {
return "0000";
}
};
// act
// assert
}
@Test
public void testBadCase() {
// arrange mock
MyHttpClient badResultClient = new MyHttpClient() {
@Override
public String connect(String url, String userId) {
return "1000";
}
};
// act
// assert
}
}
============================================================
要再複雜一點的就要用 mock library 唄。
http://code.google.com/p/mockito/
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 211.72.110.37
推
06/05 12:59, , 1F
06/05 12:59, 1F
推
06/06 12:33, , 2F
06/06 12:33, 2F
→
06/06 12:38, , 3F
06/06 12:38, 3F
→
06/06 12:41, , 4F
06/06 12:41, 4F
→
06/06 12:43, , 5F
06/06 12:43, 5F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):