I am trying to write test cases for my database.
I have a helper class that extends to SQLiteOpenHelper
DBHelper.java
public DBHelper(Context context) {
super(context, DBConstants.DATABASE_NAME, null, DBConstants.DATABASE_VERSION);
}
and a constructor class that has all the inserts deletes etc.
DBController.java
public DBController open() throws SQLException {
dbHelper = DBHelper.getInstance(context);
database = dbHelper.getWritableDatabase();
return this;
}
my test class
DBControllerTest.java
@Mock
Context mContext;
DBController dbController;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
RenamingDelegatingContext context = new RenamingDelegatingContext(mContext, "test_");
dbController = new DBController(context);
dbController.open();
}
Here when i do dbController.open(), the dbHelper.getWritableDatabase() always returns null.
How do i solve this problem. Also am I mocking it the right way. I have searched this a lot but did not find a solution. What is the best way to test database queries.
You can't mock Context like that, you need to use the instrumentation's Context. Since this test requires Android code and therefore instrumentation, make sure you put it in your test in the androidTest directory.
See this answer for an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With