I am trying to mock an SQLiteOpenHelper class in instrumented tests so whenever any fragment tries to get information from the database it returns a generic result. However, I keep getting an error saying:
org.mockito.exceptions.base.MockitoException: Cannot mock/spy class com.example.cleaningschedule.helpers.DatabaseHandler Mockito cannot mock/spy because :
- final class at com.example.cleaningschedule.ToDoListInstrumentedTest.oneTask(ToDoListInstrumentedTest.kt:81)
The test class is:
@RunWith(AndroidJUnit4::class)
class ToDoListInstrumentedTest {
    @Rule
    @JvmField var activityRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java)
    private fun getActivity() = activityRule.activity
    @After
    fun tearDown() {
        InstrumentationRegistry.getInstrumentation().getTargetContext().deleteDatabase("TaskDatabase")
    }
    @Test
    fun oneTask() {
        val mock = mock(DatabaseHandler::class.java)
        `when`(mock.getTasks()).thenThrow()
        onView(withId(R.id.taskName)).check(matches(isDisplayed()))
    }
}
The class I am trying to mock is:
class DatabaseHandler(context: Context): SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
    companion object {
    private const val DATABASE_VERSION = 5
    private const val DATABASE_NAME = "TaskDatabase"
        ...
    }
    override fun onCreate(db: SQLiteDatabase?) {
        ...
    }
    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        ...
    }    
    fun getTasks(): MutableList<Pair<MutableList<String>, MutableList<Room>>> {
        ...
    }
}
I have looked at several other similar questions but none have helped:
- Error mocking Class which hold reference to SQLiteOpenHelper
- Mock final class in java using mockito library - I had a lot of issues with import PowerMock
- How to mock a final class with mockito - I have added the dependency and created the file with the mock-maker-inlineline as suggested in the answers put I still get the same error. I also tried the answer that suggestedMockito.mock(SomeMockableType.class,AdditionalAnswers.delegatesTo(someInstanceThatIsNotMockableOrSpyable))but this gave me a 'Not enough information to infer type variable T' error
- Mock final class with Mockito 2
- Mockito cannot mock/spy because : Final Class
- Cannot mock/spy class java.util.Optional
 
    