NPE when getting Robolectric ShadowApplication with Volley and Dagger
Asked Answered
C

2

13

In my Android application I have set up Volley.

Robolectric.application is initialized and all other tests runs smoothly. I get this error when trying to get mocked HTTP response.

This is my test:

@RunWith(MyRobolectricTestRunner.class)
public class ApiTests {

    @Inject
    protected Api api;

    @Before
    public void setUp() {
        ObjectGraph.create(new AndroidModule(Robolectric.application), new TestApplicationModule()).inject(this);
    }

    @Test
    public void shouldGetErrorList() throws Exception {
        Project project = new Project("test", "test", "test", DateTime.now());
        addPendingProjectsErrorsResponse("response.json"); //adding response to FakeHttpLayer

        api.getProjectErrors(project, new Listener<ProjectErrors>() {
                @Override
                public void onResponse(ProjectErrors response) {
                    assertNotNull(response);
                }
            }, new ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    throw new RuntimeException(error);
                }
            }
        );
    }
}

This is error I get:

Exception in thread "Thread-3" java.lang.NullPointerException
    at org.robolectric.shadows.ShadowLooper.getMainLooper(ShadowLooper.java:59)
    at android.os.Looper.getMainLooper(Looper.java)
    at org.robolectric.Robolectric.getUiThreadScheduler(Robolectric.java:1301)
    at org.robolectric.shadows.ShadowSystemClock.now(ShadowSystemClock.java:15)
    at org.robolectric.shadows.ShadowSystemClock.uptimeMillis(ShadowSystemClock.java:25)
    at org.robolectric.shadows.ShadowSystemClock.elapsedRealtime(ShadowSystemClock.java:30)
    at android.os.SystemClock.elapsedRealtime(SystemClock.java)
    at com.android.volley.VolleyLog$MarkerLog.add(VolleyLog.java:114)
    at com.android.volley.Request.addMarker(Request.java:174)
    at com.android.volley.CacheDispatcher.run(CacheDispatcher.java:92)
Casease answered 9/6, 2013 at 9:19 Comment(0)
D
-2

I had same error and avoid it by using my own (and ugly) SystemClock shadow.

shadow class:

@Implements(value = SystemClock.class, callThroughByDefault = true)
public static class MyShadowSystemClock {
    public static long elapsedRealtime() {
        return 0;
    }
}

test code:

@Test
@Config(shadows = { MyShadowSystemClock.class, ... })
public void myTest() {
}
Donner answered 8/9, 2013 at 8:37 Comment(0)
I
-2

Another workaround would be to disable Volley logging by calling

VolleyLog.DEBUG = false;

in your setUp method.

Islas answered 26/11, 2013 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.