安卓测试。模拟 HttpUrlConnection(部分)

标签 android unit-testing http integration-testing android-testing

我必须创建一个测试系统来拦截所有 HTTP 请求,但应该只处理少数请求,经过一些研究我发现 this展示如何模拟 HttpUrlConnection 的文章,但我必须适应,我只想将其用于测试中的请求,其他请求应像往常一样通过互联网,我的尝试是返回不同的 HttpUrlConnection 对象,这些对象取决于 url 和显然没有用。

    public class MockURLStreamHandler extends URLStreamHandler implements URLStreamHandlerFactory
{
    ..............................
    // *** URLStreamHandler

    @Override
    protected URLConnection openConnection(URL u) throws IOException {

        mConnection = new MockHttpURLConnection(u);
        if(u.toString().equals(myTestUrl))
        {
           return mConnection;
         }
        else
        {
          //this doesn't work 
            return new HttpUrlConnection(u){..}
       }  
    }
    ...............................
}

有什么想法吗?在我应该寻找什么之后?

提前致谢。

最佳答案

看看MockWebServer

This library makes it easy to test that your app Does The Right Thing when it makes HTTP and HTTPS calls. It lets you specify which responses to return and then verify that requests were made as expected.

Because it exercises your full HTTP stack, you can be confident that you're testing everything. You can even copy & paste HTTP responses from your real web server to create representative test cases. Or test that your code survives in awkward-to-reproduce situations like 500 errors or slow-loading responses.

关于安卓测试。模拟 HttpUrlConnection(部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40003803/

相关文章:

c# - 测试 WebApi Controller 时如何生成 Asp.net 用户身份

c# - 除非打开 diff 工具,否则 ApprovalTests DiffReporter 不会弹出 diff 窗口

php - 我的 GET 变量被转义了吗?

java - 如何使用 IBM X-Force Exchange API?

android - 无法在 onActivityResult() 中获取数据

android - Firebase blaze 计划相关查询

android - 不同布局中的按钮定位

java - 创建文件夹

c# - 测试 Refit 实现的 API 时出现 NullReferenceException

api - 过滤条件的查询字符串与资源路径