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

How can I test a Robospice GoogleHttpClientSpiceRequest? Currently getting NullPointerException for HttpRequestFactory

我正在尝试测试从 GoogleHttpClientSpiceRequest.

扩展而来的 class 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,因为它是最终的 class。如何正确测试此请求?

勾选wiki page for testing RoboSpice requests(第二个例子)。经过简单的修改应该可以解决你的问题:

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

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