mardi 17 février 2015

Use mock db when testing with Robolectric and ORMLite

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



public class MyDatabaseHelper extends OrmLiteSqliteOpenHelper {
...

private static final String DATABASE_NAME = "mydb.sqlite";
private static MyDatabaseHelper helper = null;

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

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


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



public class ProductsProvider {

public static List<Products> getProducts(Context context) {
MyDatabaseHelper helper = MyDatabaseHelper.getHelper(context);
Dao<Product, String> daoProducts = helperDatabase.getProductDao();
...
...
...
}
}


I have in place Robolectric 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, prefilled with the same structure and data I normally have, 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 ProductsProviderTest extends MyTestCase {

@Test
public void testDb() {
List<Products> products = ProductsProvider.getProducts(getTestContext());
assertNotNull(products);
assertFalse(products.isEmpty());
}
}


Notice that ProductsProvider.getProducts() will use MyDatabaseHelper, which will use the db in the standard location of the Android app, and not my local file. How can modify my code for the tests to have the tests using a local db added as an asset or a resource, without touching the real code of the app?


Aucun commentaire:

Enregistrer un commentaire