单元测试中的 Sugar orm 产生了空指针异常

Sugar orm in unit test produced null pointer exception

我想做的是实施单元测试,但我需要先清除数据库。

问题是有时清除数据库失败并出现 NullPointerException。

基本上我在我拥有的每个 DTO 上调用 deleteAll 方法(例如 BusinessUnit.deleteAll(BusinessUnit.class)。有时这会失败(尽管并非总是如此)。

空指针来源于SugarRecord自己的方法:

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);
}

是什么导致了这个错误?

首先让sugarorm启动。你必须首先启动 SugarOrm。这个任务需要一些时间。因此添加以下内容:

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);
}