android - 如何测试 Robospice GoogleHttpClientSpiceRequest?当前正在为 HttpRequestFactory 获取 NullPointerException

标签 android testing robospice

我正在尝试测试从 GoogleHttpClientSpiceRequest 扩展的类 CachedGetRequest

下面的例子here我写了这个测试:

@LargeTest
public class CachedGetRequestTest extends InstrumentationTestCase {

    private MockWebServer mServer;
    private CachedGetRequest<Product> mCachedGetRequest;

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        mServer = new MockWebServer();
        mServer.enqueue(new MockResponse().setBody(...));
        mServer.start();
        URL url = mServer.getUrl("/api/products/");

        mCachedGetRequest = new CachedGetRequest<>(Product.class, url.toString(), "", "");
    }

    public void testLoadDataFromNetwork() throws Exception {
        Product product = mCachedGetRequest.loadDataFromNetwork();
        assertTrue(product.getName().equals("Test"));
    }
}

但是我得到一个错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.api.client.http.HttpRequest com.google.api.client.http.HttpRequestFactory.buildRequest(java.lang.String, com.google.api.client.http.GenericUrl, com.google.api.client.http.HttpContent)' on a null object reference

如果我尝试使用像示例中使用的 SimpleTextRequest 这样的简单请求,那么它工作得很好。所以它适用于基本的 SpiceRequest 但不适用于 GoogleHttpClientSpiceRequest

我看到 HttpRequestFactory 为空,但我该如何设置它?我可以根据请求调用 setHttpRequestFactory,但我无法使用 Mockito 模拟 HttpRequestFactory,因为它是最终类。如何正确测试此请求?

最佳答案

检查 wiki page for testing RoboSpice requests (第二个例子)。经过简单的调整后,它应该可以解决您的问题:

...
@Override
protected void setUp() throws Exception {
    // ...
    // your setup code, as specified in the question
    // ...

    mCachedGetRequest.setHttpRequestFactory(GoogleHttpClientSpiceService.createRequestFactory());
}
...

关于android - 如何测试 Robospice GoogleHttpClientSpiceRequest?当前正在为 HttpRequestFactory 获取 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29643487/

相关文章:

android - 如何在动态 View 中只选择一个复选框

android - 外部链接到 Firebase 存储上存储的文件?

android - NFC typeb 卡未被任何 NFC 应用程序检测到(如 :nfctaginfo)

javascript - 以编程方式确定 SVG 路径生成的形状

ios - XCode 11.4 - 在 UITest 中重新安装应用程序失败 : "Could not locate installed application"

android - 如何在 Samsung Galaxy S3 中加载大布局?

C++测试与菜单应用

android - 使用同步适配器 Volley/RoboSpice 同步处理网络请求

robospice - 如何同步执行 RoboSpice 请求?

android - Android 中的作业管理器