其他分享
首页 > 其他分享> > 如何在Android测试中正确模拟HttpGet调用

如何在Android测试中正确模拟HttpGet调用

作者:互联网

我有一个使用HttpGet执行HTTP GET调用的应用程序,我想模拟响应,以便测试不同的场景,而无需设置任何特定的本地服务器,就像远程一样.

目标是进行非常高级别的测试,其作用类似于真实用户(Robotium),并伪造应用程序将获得的响应,调用真实服务器.就像测试Twitter客户端一样,如果你需要一个例子.

解决方法:

好的,所以这就是我在Robotium测试中得到的假HttpResponses:
– 我有一个类HttpCallBuilder,它通常只返回一个DefaultHttpClient
– 我添加了一个setHttpClient()方法来在我的测试中设置一个MockHttpClient(你需要在HttpClient接口中实现(清空)很多方法,我在这里省略了):

public class MockHttpClient implements HttpClient {

private static Context context;
private final BasicHttpParams params = new BasicHttpParams();

@Override
public HttpResponse execute(HttpUriRequest request) throws IOException,
        ClientProtocolException {
    InputStream mockInputStream = context.getAssets().open(
            MockResponses.forRequest(request));
    return new MockHttpResponse(mockInputStream);
}

@Override
public HttpParams getParams() {
    return params;
}

public static void setContext(Context applicationContext) {
    MockHttpClient.context = applicationContext;
}
}

MockResponses允许您根据情况对正确的响应进行模拟:

public class MockResponses {

private static final List<String[]> responseMapping = new ArrayList<String[]>();
private static final String BASE = "mocks/";

public static String forRequest(final HttpUriRequest request) {
    final String requestString = request.getURI().toString();
    for (final String[] mapping : responseMapping) {
        if (requestString.matches(mapping[0])) {
            return BASE + mapping[1];
        }
    }
    throw new IllegalArgumentException(
            "No mocked reply configured for request: " + requestString);
}

public static void forRequestDoAnswer(final String regex,
        final String fileToReturn) {
    responseMapping.add(new String[] { regex, fileToReturn });
}

public static void reset() {
    responseMapping.clear();
}
}

在测试中,您可以像这样准备测试:

HttpCallBuilder.setHttpClient(new MockHttpClient());
MockHttpClient.setContext(context);
MockResponses.reset();
MockResponses.forRequestDoAnswer(".*method=Login.*", "loginform.html");

标签:robotium,android,unit-testing,mocking,http
来源: https://codeday.me/bug/20190826/1726636.html