【问题标题】:Can not figure out why android test is hanging无法弄清楚为什么android测试挂起
【发布时间】:2014-06-17 10:41:00
【问题描述】:

我想测试打开线程并返回回调的函数。 每次在第一个测试用例之后,第二个测试被挂起并且在日志中我看到 ApacheSDK(32004): Exception e:java.lang.NullPointerException。当我删除 ~/.android 文件并清理项目时,错误消失了,但这并不能解决问题。 我正在使用 CountDownLatch 使测试的线程等待。 如果我要评论其中一个测试,另一个测试运行没有任何问题。我真的不明白问题是在我的代码中还是在 ADT 中。

public class HelperTest extends ActivityInstrumentationTestCase2<MainActivity> {

  @Test
  public void test_A() throws Throwable {
    TestAdInfoMock info = new TestAdInfoMock();
    final CountDownLatch latch = new CountDownLatch(1);

    when(util.execute()).thenReturn(X, Y, Z,
            T);
    final IRequest requestComplete = new IRequest() {

        @Override
        public void onReceiveInfoCompleted() {
            assertNull(“message”, …);
            assertNull("message", …);
            latch.countDown();
         }
    };

    //The requestData opens thread with AsyncTask
    Helper.requestData(context, requestComplete); 
    boolean await = latch.await(2, TimeUnit.SECONDS);
    assertTrue(await);
}

 @Test
 public void test_B() throws Throwable {
    final CountDownLatch latch = new CountDownLatch(1);

    when(util.execute()).thenReturn(X, Y, Z,
            T);

     final IRequest requestComplete = new IRequest() {

        @Override
        public void onReceiveInfoCompleted() {
            assertNull(“message”, …);
            assertNull("message", …);
            latch.countDown();
         }
    };        
    //The requestData opens thread with AsyncTask
    Helper.requestData(context, requestComplete); //

    boolean await = latch.await(2, TimeUnit.SECONDS);
    assertTrue(await);
}


@Override
protected void tearDown() throws Exception {
    super.tearDown();
    clearPreferences();
}

void clearPreferences() {
    SharedPreferences preferences = getActivity().getSharedPreferences("global", 0);
    SharedPreferences.Editor editor = preferences.edit();
    editor.remove(KEY!);
    editor.remove(KEY2);
    editor.commit();
}

}

感谢任何建议和 cmets。

编辑:

为了找出问题,我开始进行原始分析:迭代。

当从 tearDown 方法中删除 clearPreferences() 方法时,所有测试工作正常。 但我仍然不明白为什么 clearPreferences 方法应该挂起测试。

【问题讨论】:

    标签: android multithreading integration-testing mockito


    【解决方案1】:

    在 Android 中使用 CountDownLatch 时,通常在同一线程上调用 countDown 和 await 时会出现问题。

    我不知道 IRequest,但是像 onReceiveInfoCompleted 这样的回调通常在主线程上运行:

    @Override
            public void onReceiveInfoCompleted() {
                assertNull(“message”, …);
                assertNull("message", …);
                latch.countDown();
             }
    

    因此在您调用 await 的同一线程上。但是,当您首先在线程上调用 await 时,您将永远不会进入倒计时。

    【讨论】:

    • 为什么你认为 onReceiveInfoCompleted 在主线程上运行?
    猜你喜欢
    • 2015-06-08
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2014-12-08
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多