0

我被困住了,很高兴得到任何帮助!

我正在为一个 android 库编写测试。任务是在活动中进行一些操作并检查库是否正确响应。我的问题是,我的测试在活动中的所有操作完成后就完成了,但是我通过回调获得了测试结果(只有在测试结束时我才会收到这个回调)。所以,我想以某种方式告诉测试框架,直到收到回调(或直到时间用完),测试才结束。这是我现在拥有的:

@Test
public void testSimpleSetup() {

    /* ... */

    InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
        @Override
        public void run() {
            testManager.startTest(MAX_WAIT_TIME); // this object calls onTestResult(boolean) after time t (t <= MAX_WAIT_TIME)

            /* working with activity here */
        }
    });
    InstrumentationRegistry.getInstrumentation().waitForIdleSync();
}

@Override
public void onTestResult(boolean passed) {
    // assertTrue(passed);
    Assert.fail();
}

我预计这个测试会失败,但实际上onTestResult是在testSimpleSetup完成后调用,并且 Assert 对测试结果没有影响。

提前致谢。

4

2 回答 2

2

检查这篇文章。我修改了一些代码,因为我阅读了以下内容

与单参数版本一样,中断和虚假唤醒是可能的,并且应该始终在循环中使用此方法:

Object mon = new Object(); //reference in your Activity
boolean testOnGoing = true;
/*...*/

InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
        @Override
        public void run() {
           synchronized (mon) {
           testManager.startTest(MAX_WAIT_TIME); 
           /* working with activity here */
           while(testOnGoing)
              mon.wait();
           } 
        }
});

InstrumentationRegistry.getInstrumentation().waitForIdleSync();
}

@Override
public void onTestResult(boolean passed) {
synchronized (mon) {    
    //assertTrue(passed);
    Assert.fail();
    testOnGoing = false;
    mon.notify();
   } 
}
于 2015-05-26T18:41:59.547 回答
1

感谢@Gordak。他的回答几乎奏效了。但是,不幸的是,它阻塞了主线程,所以测试永远不会结束。我对其进行了一些修改,所以现在它可以工作了。

@Before
public void setUp() throws Exception {
    activity = testRule.getActivity();
    latch = new CountDownLatch(1);
}

@Test
public void testSimpleSetup() {

    /* ... */

    InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
        @Override
        public void run() {
            testManager.startTest(MAX_WAIT_TIME); // this object calls onTestResult(boolean) after time t (t <= MAX_WAIT_TIME)

            /* working with activity here */
        }
    });
    InstrumentationRegistry.getInstrumentation().waitForIdleSync();

    latch.await(); // here we block test thread and not UI-thread
                   // presumably, you will want to set the timeout here
}

@Override
public void onTestResult(boolean passed) {
    // assertTrue(passed);
    Assert.fail();
    latch.countDown();
}
于 2015-05-27T12:46:25.353 回答