【发布时间】:2018-07-25 10:04:02
【问题描述】:
我编写了一个调用我的服务并通过广播接收答案的 Android 插桩测试。
要测试的代码,它与服务对话,使用处理程序。
在测试我的测试过程中 ^^ 我注意到处理程序的行为不符合预期。所以我写了一个测试来检查这种行为:
import android.os.Handler;
import android.support.test.annotation.UiThreadTest;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@RunWith(AndroidJUnit4.class)
public class HandlerTest {
private CountDownLatch countDownLatch;
@Test
@UiThreadTest
public void handlerTest() {
final Handler handler = new Handler();
countDownLatch = new CountDownLatch(1);
final Runnable r = new Runnable() {
@Override
public void run() {
// this code gets not executed
countDownLatch.countDown();
}
};
handler.postDelayed(r, 1000);
try {
final boolean finishedWithoutTimeout
= countDownLatch.await(5, TimeUnit.SECONDS);
Assert.assertTrue(finishedWithoutTimeout);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
处理程序不执行可运行代码。这也是我的生产代码的问题。
我遇到了Looper.prepare() 的问题,我使用@UiThreadTest 注释解决了这个问题。
对我的处理程序问题有什么建议吗?
【问题讨论】:
-
@MartinZeitler 谢谢,但这并不能真正解决我的问题。
标签: java android testing android-service android-handler