Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing SQLiteOpenHelper test cases in JUnit4 and Mockito

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.

like image 227
android_eng Avatar asked Nov 24 '25 21:11

android_eng


1 Answers

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.

like image 127
telkins Avatar answered Nov 26 '25 11:11

telkins