简体   繁体   English

Android单元测试和数据库处理程序

[英]Android Unit Tests and Database Handler

I'm a little lost on how to properly test the database of my Android application. 我对如何正确测试Android应用程序的数据库有些迷惑。 I have my Database Handler which extends SQLiteOpenHelper. 我有扩展SQLiteOpenHelper的数据库处理程序。 Some solutions advise mocking this class, but how will that get me a separate instance of my database? 一些解决方案建议模拟此类,但是如何使我获得数据库的单独实例? I also see the suggestion to use an in-memory SQLite database but that seems like a lot of unnecessary juggling... 我也看到了使用内存中SQLite数据库的建议,但这似乎有很多不必要的麻烦。

How should I be testing my database? 我应该如何测试我的数据库? Any help appreciated. 任何帮助表示赞赏。

This is how I did for my database library: 这是我对数据库库所做的操作:

public class TestDatabaseManager extends AndroidTestCase {

    HrSuiteDatabaseManager dbm;

    public void setUp() throws Exception {
        super.setUp();

        RenamingDelegatingContext rdcontext = new RenamingDelegatingContext(getContext(), "test_");
        dbm = new HrSuiteDatabaseManager(rdcontext);
        dbm.registerTableAccess(new EmployeeAccess());
    }

    public void testInsertion() {
        EmployeeAccess ea = dbm.getEmployeeAccess();
        ea.insert(createEmployee(0));

        List<Employee> emps = ea.getAll();
        assertEquals(1, emps.size());

        assertEmployee(emps.get(0), 0);
    }
}

The key here is the class RenamingDelegatingcontext that will create the database file with specified prefix. 此处的关键是类RenamingDelegatingcontext ,它将使用指定的前缀创建数据库文件。

I have HrSuiteDatabaseManager that is derived from SQLiteOpenHelper . 我有HrSuiteDatabaseManager是源自SQLiteOpenHelper I instantiate it using RenamingDelegatingcontext and use it in my test cases as usual. 我使用RenamingDelegatingcontext实例化它,并像往常一样在测试用例中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM