androidkotlinmockitoandroid-unit-testing

Mockito to mock final field of class


I am trying to mock a final field of class Student

data class Student(
    val id: Int,
    val name: String,
    val marks: Marks
)

data class Marks(
    val subject1: String
)

and this is my test class

class StudentTest {

    @Test
    fun testStudentMarks() {
        val student = mock(Student::class.java)
        assertNotNull(student.id)
        assertNotNull(student.marks)
    }

}

On running test it passes student.id but it fails on student.marks with the below error

junit.framework.AssertionFailedError
    at junit.framework.Assert.fail(Assert.java:55)
    at junit.framework.Assert.assertTrue(Assert.java:22)
    at junit.framework.Assert.assertNotNull(Assert.java:256)
    at junit.framework.Assert.assertNotNull(Assert.java:248)
    at com.example.mockitotest.StudentTest.testStudentMarks(StudentTest.kt:16)

How can I mock marks field


Solution

  • Since it's a Kotlin class, you can just do

    Mockito.when(student.id).thenReturn(0)
    

    or

    val m = Mockito.mock(Marks::class.java)
    Mockito.when(student.marks).thenReturn(m)