3

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.

android_eng
  • 1,370
  • 3
  • 17
  • 40

1 Answers1

4

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.

Community
  • 1
  • 1
telkins
  • 10,440
  • 8
  • 52
  • 79
  • How do i use a dependency for both unit tests cases and instrument test cases i.e. use mockito as both androidTestCompile and testCompile. – android_eng Mar 02 '16 at 14:10
  • @Rohit_Ramkumar Just declare it for both, eg `testCompile ` `androidTestCompile ` – telkins Mar 02 '16 at 15:43