如何使用Android的激活与在内存数据库使用Robolectric单元测试? [英] How can I use Active Android with an in memory database for unit tests using Robolectric?

查看:281
本文介绍了如何使用Android的激活与在内存数据库使用Robolectric单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说。我知道,有一个限制在robolectric提供的内存数据库。有没有办法使用此与Active Android的?在默认配置中,看来该数据库被清除所有的测试运行之后,但不是每个测试

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.

推荐答案

我用greenDao - 但原理是一样的。

I use greenDao - but the principle is the same.

我的应用程序类初始化我的DB(数据库都有一个名称)。对于我的测试中,我继承应用程序(它允许Robolectric调用此版本代替),并覆盖,获取数据库名称的方法 - 和返回null。这就意味着我在内存数据库创建。由于应用程序的创建是安装程序的一部分,那么在内存中一个新的数据库,用于每个测试。

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

这篇关于如何使用Android的激活与在内存数据库使用Robolectric单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆