同步CursorLoader测试用例的最佳实践

时间:2013-09-15 19:17:31

标签: android junit android-contentprovider android-testing android-cursorloader

我刚刚切换到使用CursorLoaders,我在编写使用它们的测试时遇到了麻烦。由于使用CursorLoader方法,主要线程getInstrumentation().waitForIdleSync()的查询在更新适配器之前返回(或者至少这是我的理论)。我试图避免这是我的所有测试

public void testUpdateList() throws InvalidRecord, InterruptedException {
    ListView listView = frag.getListView();
    // Verify list is empty
    assertEquals(0, listView.getCount());

    // Add transaction directly into database
    transTable.addOccurrences(resolver, TestUtils.createMockTrans());

    //Don't want to do this but it works.   
    synchronized (this) {
        wait(500);
        assertEquals(1, listView.getCount());
    }
}

所以我的问题是,有没有更好的方法在Android测试框架中测试这个功能?

1 个答案:

答案 0 :(得分:1)

我解决的解决方案是在Robotium中使用waitForCondition方法。这是一个例子。

...
 // Waits for 500 milliseconds for the condition to be meet.  
 // If it isn't meet within this time limit the result is false.
 boolean isSatisfied =  solo.waitForCondition( new Condition() {
    public boolean isSatisfied() {
      return listView.getCount() == 1;
    }, 500);

  //Then I check if the condition has been meet.
  assertTrue(isSatisfied);
...