【问题标题】:Handler not executing Runnable in Instrumentation Test处理程序未在 Instrumentation Test 中执行 Runnable
【发布时间】: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 注释解决了这个问题。

对我的处理程序问题有什么建议吗?

【问题讨论】:

标签: java android testing android-service android-handler


【解决方案1】:

原因是你把你的thread锁在这里了:

final boolean finishedWithoutTimeout = countDownLatch.await(5, TimeUnit.SECONDS);

thread 被锁定时,您无法使用handler 发送rannableThread 刚刚被锁定。 您可以通过将您的 handler 链接到另一个 thread 来解决它。这是通过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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多