【发布时间】:2017-02-16 14:38:42
【问题描述】:
根据 Espresso 文档,仪器测试应自动等待 AsyncTasks 完成。但它不起作用。我创建了这个简单的测试用例:
package foo.bar;
import android.os.AsyncTask;
import android.support.test.annotation.UiThreadTest;
import android.support.test.filters.LargeTest;
import android.support.test.rule.UiThreadTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class ExampleInstrumentedTest {
private static final String TAG = "ExampleInstrumentedTest";
@Rule public UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();
@Test
@UiThreadTest
public void testAsyncTask() throws Throwable {
Log.d(TAG, "testAsyncTask entry");
uiThreadTestRule.runOnUiThread(() -> new AsyncTask<String, Void, Integer>() {
@Override
protected Integer doInBackground(String... params) {
Log.d(TAG, "doInBackground() called with: params = [" + params + "]");
try {
Thread.sleep(2000);
} catch (InterruptedException ignored) {
}
return params.length;
}
@Override
protected void onPostExecute(Integer integer) {
Log.d(TAG, "onPostExecute() called with: integer = [" + integer + "]");
assertEquals(3, (int) integer);
throw new RuntimeException("this should fail the test");
}
}.execute("One", "two", "three"));
Log.d(TAG, "testAsyncTask end");
}
}
返回 UI 线程时测试应该失败,但它总是成功。 这是测试的 logcat 输出:
I/TestRunner: started: testAsyncTask(foo.bar.ExampleInstrumentedTest)
D/ExampleInstrumentedTest: testAsyncTask entry
D/ExampleInstrumentedTest: testAsyncTask end
I/TestRunner: finished: testAsyncTask(foo.bar.ExampleInstrumentedTest)
D/ExampleInstrumentedTest: doInBackground() called with: params = [[Ljava.lang.String;@8da3e9]
正如您所见,测试甚至在后台方法执行之前就完成了。 我怎样才能让测试等待它?
【问题讨论】:
标签: java android testing android-asynctask android-espresso