How can I use Active Android with an in memory database for unit tests using Robolectric?

非 Y 不嫁゛ 提交于 2019-12-22 04:40:06

问题


As the title says. I am aware that there is a limited in memory database provided in robolectric. Is there any way to use this with Active Android? Under the default configuration, it appears that the database is cleared after all the tests are run, but not for each test.


回答1:


I use greenDao - but the principle is the same.

My Application class initialises my DB (the DB has a name). For my tests I subclass Application (which allows Robolectric to call this version instead) and override the method that gets the DB name - and return null. This then means I create an in memory DB. As the Application creation is part of setUp then a new in memory DB is used for each test.

public class MyApplication extends android.app.Application {
    @Override
    public void onCreate() { 
        super.onCreate(); 
        initialiseDB(getDatabaseName()); 
    } 

    protected String getDatabaseName() { 
        return "regular-db-name"; 
    }

    private void initialiseDB(String dbName) {
        // DB initialization

        // one example would be:
        Configuration.Builder builder = new Configuration.Builder(this);
        builder.setDatabaseName(dbName);
        ActiveAndroid.initialize(builder.create());
    }
}

public class TestApplication extends MyApplication {
    @Override
    protected String getDatabaseName() { 
        // use fresh in memory db each time 
        return null; 
    } 
}


来源:https://stackoverflow.com/questions/19690811/how-can-i-use-active-android-with-an-in-memory-database-for-unit-tests-using-rob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!