作者qrtt1 (有些事,有時候。。。)
看板java
標題Re: [問題] 與網路狀態相關的Test Case該怎麼寫
時間Tue Jun 5 12:28:17 2012
※ 引述《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
推 MIDlet:我去研究看看 06/05 12:59
推 MIDlet:感謝qrtt1,雖然最後沒有用這個方法,不過提醒了我HttpClient 06/06 12:33
→ MIDlet:應該設計成MyHttpClient的一個private field 06/06 12:38
→ MIDlet:實作一個假的HttpClient用setter指定給MyHttpClient 06/06 12:41
→ MIDlet:就可以不受網路影響來測試了 06/06 12:43