0

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

Bhavik Kasundra
  • 113
  • 1
  • 9

1 Answers1

1

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)
Demigod
  • 5,073
  • 3
  • 31
  • 49
  • But for java `when` requires only method call. As a solution can be add additional getter for final veriable. – walkmn Nov 23 '21 at 15:34
  • But `student.id` in java anyway will look like `student.getId()`, isn't it? – Demigod Nov 24 '21 at 09:49
  • @Demigon right, but the question is how to mock final field without getter. For example how to mock value for this `final` integer in Student java class: ```class Student { public final int id = 10; }``` – walkmn Nov 24 '21 at 12:14
  • 1
    Yeah. An additional getter is good when you can change this class. In case of java things are a bit complicated :) – Demigod Nov 24 '21 at 15:01