NoClassDefFoundError while 运行 Roboelectric 单元测试

NoClassDefFoundError while running Roboelectric Unit Test

我正在尝试 运行 Roboelectric 单元测试以测试预期的 activity 是否开始,但我收到以下错误:

java.lang.NoClassDefFoundError: Could not initialize class android.os.AsyncTask

我正在寻找解决方案,但到目前为止还没有成功,有没有人遇到过这个问题。

在我的测试下面找到class

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, manifest = "AndroidManifest.xml", minSdk = 21, maxSdk = 21, application = MyApplication.class)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
public class PushManagerTest {

    @Test
    public void shouldLaunchNewActivity() throws Exception {
    Activity testActivity = Robolectric.setupActivity(TestActivity.class);

    Intent expectedIntent = new Intent(testActivity, NewActivity.class);
    Intent actualIntent = ShadowApplication.getInstance().getNextStartedActivity();
    assertEquals(expectedIntent.getComponent(), actualIntent.getComponent());
    }
}

我终于修复了它,不知道它是否正确,但测试按预期工作

我必须在我的应用程序 onCreate 中添加以下行 class

try{
    Class.forName("android.os.AsyncTask");
}catch(Throwable ignore) {
        // ignored
}

希望对大家有所帮助