tôi thực hiện một lớp con của HttpStack tên FakeHttpStack rằng tải cơ thể phản ứng giả từ tập tin địa phương nằm trong res/raw. Tôi đã làm điều này cho mục đích phát triển, tức là tôi có thể phát triển một cái gì đó cho API mới trước khi máy chủ sẵn sàng, nhưng bạn có thể tìm hiểu điều gì đó (ví dụ: ghi đè HttpStack # peformRequest và createEntity) từ đây.
/**
* Fake {@link HttpStack} that returns the fake content using resource file in res/raw.
*/
class FakeHttpStack implements HttpStack {
private static final String DEFAULT_STRING_RESPONSE = "Hello";
private static final String DEFAULT_JSON_RESPONSE = " {\"a\":1,\"b\":2,\"c\":3}";
private static final String URL_PREFIX = "http://example.com/";
private static final String LOGGER_TAG = "STACK_OVER_FLOW";
private static final int SIMULATED_DELAY_MS = 500;
private final Context context;
FakeHttpStack(Context context) {
this.context = context;
}
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> stringStringMap)
throws IOException, AuthFailureError {
try {
Thread.sleep(SIMULATED_DELAY_MS);
} catch (InterruptedException e) {
}
HttpResponse response
= new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
List<Header> headers = defaultHeaders();
response.setHeaders(headers.toArray(new Header[0]));
response.setLocale(Locale.JAPAN);
response.setEntity(createEntity(request));
return response;
}
private List<Header> defaultHeaders() {
DateFormat dateFormat = new SimpleDateFormat("EEE, dd mmm yyyy HH:mm:ss zzz");
return Lists.<Header>newArrayList(
new BasicHeader("Date", dateFormat.format(new Date())),
new BasicHeader("Server",
/* Data below is header info of my server */
"Apache/1.3.42 (Unix) mod_ssl/2.8.31 OpenSSL/0.9.8e")
);
}
/**
* returns the fake content using resource file in res/raw. fake_res_foo.txt is used for
* request to http://example.com/foo
*/
private HttpEntity createEntity(Request request) throws UnsupportedEncodingException {
String resourceName = constructFakeResponseFileName(request);
int resourceId = context.getResources().getIdentifier(
resourceName, "raw", context.getApplicationContext().getPackageName());
if (resourceId == 0) {
Log.w(LOGGER_TAG, "No fake file named " + resourceName
+ " found. default fake response should be used.");
} else {
InputStream stream = context.getResources().openRawResource(resourceId);
try {
String string = CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
return new StringEntity(string);
} catch (IOException e) {
Log.e(LOGGER_TAG, "error reading " + resourceName, e);
}
}
// Return default value since no fake file exists for given URL.
if (request instanceof StringRequest) {
return new StringEntity(DEFAULT_STRING_RESPONSE);
}
return new StringEntity(DEFAULT_JSON_RESPONSE);
}
/**
* Map request URL to fake file name
*/
private String constructFakeResponseFileName(Request request) {
String reqUrl = request.getUrl();
String apiName = reqUrl.substring(URL_PREFIX.length());
return "fake_res_" + apiName;
}
}
Để sử dụng FakeHttpStack, bạn chỉ cần phải vượt qua nó để bạn RequestQueue. Tôi cũng ghi đè lên RequestQueue.
public class FakeRequestQueue extends RequestQueue {
public FakeRequestQueue(Context context) {
super(new NoCache(), new BasicNetwork(new FakeHttpStack(context)));
}
}
Điểm tốt cho phương pháp này là không yêu cầu nhiều thay đổi trong mã của bạn. Bạn chỉ cần chuyển đổi Yêu cầuQueue thành FakeRequestQueue khi thử nghiệm. Do đó, nó có thể được sử dụng trong thử nghiệm chấp nhận hoặc kiểm tra hệ thống.
Mặt khác, để kiểm tra đơn vị, có thể có cách nhỏ gọn hơn. Ví dụ: bạn có thể triển khai lớp học Yêu cầu.Listener của bạn dưới dạng lớp riêng biệt để có thể dễ dàng kiểm tra phương pháp onResponse. Tôi khuyên bạn nên đặt chi tiết hơn về những gì bạn muốn thử nghiệm hoặc đặt một số đoạn mã.
Giải pháp của tôi cho phản hồi giả mạo là tạo FakeHttpStack triển khai HttpStack. Sau đó, bạn có thể nhận được RequestQueue như RequestQueue mới (new NoCache(), new BasicNetwork (new FakeHttpStack())); – Kazuki
Hiện tại không có tài liệu nào tôi có thể tìm thấy. Nhưng có rất nhiều mẫu và video Google IO 2013 cũng dễ dàng đào sâu. –
@Kazuki Bạn có thể để điều đó như một câu trả lời không? Cho đến nay nó là câu trả lời thực sự duy nhất ở đây. –