根據Espresso文檔,儀器測試應自動等待AsyncTasks
完成。但它不起作用。我創建了這個簡單的測試用例:Espresso不等AsyncTask完成
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]
正如你可以看到測試結束時,即使執行後臺方法之前。 我該如何讓測試等待呢?
正如你可以按預期它不工作日誌消息看。測試完成後調用doInBackground()方法,並且甚至不調用onPostExecute()。在完成測試之前,Espresso應該等待後臺操作完成。這可以是Thread.sleep()可以模擬的任何長時間運行的任務。 – McFarlane
@MFFarlane你是否按照我的建議去做? –
我沒有,因爲這不會反映測試用例。想象一下,通過網絡操作取代Thread.sleep。你不能從onPostExecute運行這些。 – McFarlane