【发布时间】:2017-07-05 23:26:42
【问题描述】:
我想测试在 AsyncTask 中执行的方法。我已经嘲笑了里面的所有方法。我有什么 -
- 获取所有必需参数并执行 new 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)
如何使用 robolectric、powermock 测试 AsyncTask?
更新:
正如我看到的ShadowApplication.getInstance() == null,这就是为什么我在调用“flushBackgroundThreadScheduler”时收到 NPE 异常。
我创建了custom runner to create custom application,但它仍然为空。
修复迁移到的应用程序中的 NPE:
testCompile "org.robolectric:robolectric:3.0"
更新:
当我在 @Test 中创建 AsyncTask 时 - 它可以工作
new AsyncTask() {
@Override
protected Object doInBackground(Object[] params) {
System.out.println("empty async task");
return null;
}
}.execute();
ShadowApplication.runBackgroundTasks();
Robolectric.flushBackgroundThreadScheduler();
使用“静态”方法创建任务时会出现问题
【问题讨论】:
标签: android unit-testing android-asynctask robolectric powermockito