Sugar orm in unit test produced null pointer exception

800 views Asked by At

What I'm trying to do is implement a unit test, but I need to clear the database before it.

The problem is that sometimes clearing database fails with NullPointerException.

Basicily I call deleteAll method on every DTO I have (for example BusinessUnit.deleteAll(BusinessUnit.class). And sometimes this fail (though not always).

Null pointer originates from SugarRecord's own method:

public static <T extends SugarRecord<?>> void deleteAll(Class<T> type) {
    Database db = SugarApp.getSugarContext().getDatabase();
    SQLiteDatabase sqLiteDatabase = db.getDB(); // exception is thrown here
    sqLiteDatabase.delete(getTableName(type), (String)null, (String[])null);
}

What could have caused this error?

1

There are 1 answers

3
Lunero On BEST ANSWER

Let the sugarorm start up at first. You have first to let start the SugarOrm. This task needs some time. Therefore add the following:

public class ApplicationTest extends ApplicationTestCase<Application> {
@Override
public void setUp() throws Exception {
    super.setUp();

    // SugarORM need some time to start up, else tests will fail
    Thread.sleep(3000);
}