Java 处理程序未在检测测试中执行Runnable
我已经编写了一个Android测试,它调用我的服务并通过广播接收答案 与服务对话的待测试代码使用处理程序 在测试我的测试的过程中^^^我注意到处理程序的行为不符合预期。所以我写了一个测试来检查这种行为:Java 处理程序未在检测测试中执行Runnable,java,android,testing,android-service,android-handler,Java,Android,Testing,Android Service,Android Handler,我已经编写了一个Android测试,它调用我的服务并通过广播接收答案 与服务对话的待测试代码使用处理程序 在测试我的测试的过程中^^^我注意到处理程序的行为不符合预期。所以我写了一个测试来检查这种行为: import android.os.Handler; import android.support.test.annotation.UiThreadTest; import org.junit.Assert; import org.junit.Test; import java.util.c
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();
}
}
}
处理程序不执行可运行代码。这也是我的生产代码的问题
我用@UiThreadTest
注释修复了Looper.prepare()
的问题
关于我的处理程序问题有什么建议吗?原因是您在此处锁定了
线程:
final boolean finishedWithoutTimeout = countDownLatch.await(5, TimeUnit.SECONDS);
当线程
被锁定时,您无法使用处理程序
发送rannable
。线程刚刚被锁定。
您可以通过将处理程序
链接到另一个线程
来解决此问题。下面是一个通过handlerThread
实现的简单解决方案:
@Test
@UiThreadTest
public void handlerTest() {
countDownLatch = new CountDownLatch(1);
final HandlerThread handlerThread = new HandlerThread("solution!");
handlerThread.start();
final Runnable r = new Runnable() {
@Override
public void run() {
countDownLatch.countDown();
}
};
Handler handler = new Handler(handlerThread.getLooper());
handler.postDelayed(r, 1000);
try {
final boolean finishedWithoutTimeout = countDownLatch.await(5, TimeUnit.SECONDS);
Assert.assertTrue(finishedWithoutTimeout);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
@MartinZeitler谢谢,但这并不能真正解决我的问题。