Search code examples
androidtestingrobospice

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


I'm trying to test my class CachedGetRequest which extends from GoogleHttpClientSpiceRequest.

Following the example here I have written this test:

@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"));
    }
}

But I am getting an error:

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

If I try using a simple request like the SimpleTextRequest used in the example, then it works just fine. So it works for a basic SpiceRequest but not for a GoogleHttpClientSpiceRequest.

I see that the HttpRequestFactory is null but how can I set it? I can call setHttpRequestFactory on the request but I cannot mock a HttpRequestFactory with Mockito as it's a final class. How can I correctly test this Request?


Solution

  • Check the wiki page for testing RoboSpice requests (second example). It should address your problem after a simple adaptation:

    ...
    @Override
    protected void setUp() throws Exception {
        // ...
        // your setup code, as specified in the question
        // ...
    
        mCachedGetRequest.setHttpRequestFactory(GoogleHttpClientSpiceService.createRequestFactory());
    }
    ...