3

During many of my tests, my app is running AsyncTasks that access the database and cannot be cancelled. At the end of my tests, I close my database, delete it, then reopen it so I have a fresh database fixture.

The problem is that when the AsyncTasks happen to still be running during the time when the test is closing and deleting the database, I'll get a runtime exception in the code. This couldn't ever happen in the production code because the database is never closed in production.

Robotium has a test helper method called finishOpenedActivities that I use in my test teardown method. If there were some way to modify the finishOpenedActivities to ensure that all child threads (AsyncTasks specifically) were finished as well, that would be tremendously helpful. Otherwise I probably have to go implement checks for cancelled in all my AsyncTasks just to support reliable testing.

Is there were some way to wait until all child threads (AsyncTasks specifically) are finished?

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246

2 Answers2

1

There is a getStatus() method according to the docs. You just need a reference to the AsyncTask.

AsyncTask<Void, Void, Void> yourAsyncTask = new AsyncTask<Void, Void, Void>() {

    @Override
    protected Void doInBackground(Void... arg0) {
        // your async code           

        return null;
    }

};

if (yourAsyncTask.getStatus() == AsyncTask.Status.RUNNING) {
    // What ever you need to do if still running ex.

    yourAxyncTask.cancel();
}
Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
bytebender
  • 7,371
  • 2
  • 31
  • 54
0

I ended up sidestepping the database issue, though this is pretty tool-dependent for anyone else to likely find useful. I also use OrmLite for my database access, so I added logic inside the test teardown method that uses reflection via PowerMock's Whitebox to access OrmLite's private database instanceCount variable. It keeps track of how many database handles are open. I just wait until the handle count goes down to one, and then I know that there are no other threads accessing the database.

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246