0

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:

T. Green
  • 323
  • 10
  • 20

1 Answers1

0

I will made an Interface :

public interface ContainerHandler {
    MutableList<Pair<MutableList<String>, MutableList<Room>>> getTasks();
}

Then I made DatabaseHandler inherit this interface, I call Mockito's mock function with the Interface.

val mock = mock(ContainerHandler::class.java)
    `when`(mock.getTasks()).thenThrow()

And finally I inject my mock into the tested class.

Julien Gavard
  • 613
  • 1
  • 6
  • 20
  • Thank you for the answer, I am not sure how to make an interface of the class. I tried wrapping the the class in an interface but then I can't find the function `getTasks()`. I tried creating a separate interface and then implementing the interface in the `DatabaseHandler` class but this still gives me the same error as before – T. Green Jul 03 '21 at 09:17
  • I modify my answer to add more precision. Sorry, I'm not behin my computer – Julien Gavard Jul 03 '21 at 09:27
  • Thank you, I understand this better now. Doing this stops the error but the `getTasks()` function doesn't actually get mocked when testing the app so the `getTasks()` function is called as normal. – T. Green Jul 03 '21 at 19:01