android – NPE当与Volley和Dagger获得Robolectric ShadowApplication时

前端之家收集整理的这篇文章主要介绍了android – NPE当与Volley和Dagger获得Robolectric ShadowApplication时前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的 Android应用程序中,我已经设置了Volley.

Robolectric.application被初始化,所有其他测试运行顺利.
尝试得到嘲笑的HTTP响应时,我收到此错误.

这是我的考验

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

这是我得到的错误

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)

解决方法

我有同样的错误,并避免使用我自己(和丑)的SystemClock阴影.

影子类:

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

测试代码

@Test
@Config(shadows = { MyShadowSystemClock.class,... })
public void myTest() {
}

猜你在找的Android相关文章