Use local db when testing with Robolectric 3 and ORMLite

时间:2015-10-29 15:55:22

标签: android sqlite ormlite robolectric android-testing

I am working on an Android app that uses OrmLite to connect to the SQLite db.

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
...

private static final String DATABASE_NAME = "db.sqlite";
private static DatabaseHelper helper = null;

private DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, BuildConfig.DATABASE_VERSION);
}

public static synchronized DatabaseHelper getHelper(Context context) {
    if (helper == null) {
        helper = new DatabaseHelper(context);
    }
    return helper;
  }
}

To fetch data from the db, I have some helper classes, they use some DAO.

public class AccountsDBHelper {

public List<Account> getAllAccounts(Context context) {

    DatabaseHelper dbHelper = DatabaseHelper.getHelper(context);
    Dao<Acount, Integer> daoAccounts = dbHelper.getAccountsDao();
    ...
    ...
    ...
      }
}

I have in place Robolectric 3 to test my code, but I am having hard time to understand how to use together Robolectric with ORMLite. My idea is to have a mock database.sqlite in assets, following the same structure as the one I have in production. This database will be prefilled with data from test accounts, and use that for all my tests. For example, if I want to test the ProductsProvider class, I should do:

@RunWith(MyTestRunner.class)
public class AccountsDBHelperTest {

@Test
public void testGetAllAccounts() {
    List<Accounts> accounts= AccountsDBHelper.getAllAccounts(getTestContext());
    assertNotNull(accounts);
    assertFalse(accounts.isEmpty());
    }
}

Notice that AccountsDBHelper.getAllAccounts() will use the DatabaseHelper, which will use the db in the Android app assets, and not my local production database file. How can I modify my code of the tests to have them using a local db added as an asset ? Without touching the real code of the app? Any help will be very welcome, thank you...

1 个答案:

答案 0 :(得分:0)

缺少的链接指向本地数据库的路径 String dbPath = RuntimeEnvironment.application.getPackageResourcePath() + DB_FOLDER + dbName;