我想测试在AsyncTask中执行的方法。我已经嘲笑了里面的所有方法。我有 -Robolectric AsyncTask回调
- 获取所有必需参数并执行新的AsyncTask()的静态方法executeOnExecutor();
- 在onPostExecute()我调用结果的回调。
为了测试我使用:
testCompile 'junit:junit:4.12'
testCompile "org.robolectric:robolectric:3.2.2"
testCompile "org.powermock:powermock-module-junit4:1.6.4"
testCompile "org.powermock:powermock-module-junit4-rule:1.6.4"
testCompile "org.powermock:powermock-api-mockito:1.6.4"
testCompile "org.powermock:powermock-classloading-xstream:1.6.4"
但回调不会被调用。例如:
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 24,
application = StubApplicationClass.class)
@PowerMockIgnore({"org.mockito.", "android.*"})
@PrepareForTest(BaseHttpClient.class)
@SuppressStaticInitializationFor("io.realm.internal.Util")
public class GetDataTest {
@Rule
public PowerMockRule rule = new PowerMockRule();
....................................
@Test
public void getDataTest() throws Exception {
System.out.println("started");
BaseAsyncClient.doAsync(UserPublicDataTable, Actions,
list, new IHttpResponse<String>() {
@Override
public void httpResponse(@Nullable String response) {
assertNotNull(response); System.out.println("onPostExecute()");
}
});
System.out.println("finished");
}
onPostExecute - 从不打印。
当我打电话:
Robolectric.flushBackgroundThreadScheduler();
我收到异常:
java.lang.NullPointerException
at org.robolectric.Robolectric.getBackgroundThreadScheduler(Robolectric.java:193)
at org.robolectric.Robolectric.flushBackgroundThreadScheduler(Robolectric.java:200)
如何测试的AsyncTask与robolectric,powermock?
更新:
当我看到ShadowApplication.getInstance() == null
,这就是为什么我收到NPE异常,当调用 'flushBackgroundThreadScheduler
'。
我创建了custom runner to create custom application,但它仍然为空。
要解决NPE在应用程序迁移到:
testCompile "org.robolectric:robolectric:3.0"
UPDATE:
当我在@Test创建的AsyncTask - 它的工作原理
new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
System.out.println("empty async task");
return null;
}
}.execute();
ShadowApplication.runBackgroundTasks();
Robolectric.flushBackgroundThreadScheduler();
所以问题时,任务与创建“静态'方法