Mockito 模拟 class 的最终字段

Mockito to mock final field of class

我正在尝试模拟 class 学生

的最终字段
data class Student(
    val id: Int,
    val name: String,
    val marks: Marks
)

data class Marks(
    val subject1: String
)

这是我的测试class

class StudentTest {

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

}

在 运行 测试中它通过 student.id 但在 student.marks 上失败并出现以下错误

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)

如何模拟标记字段

因为它是 Kotlin class,你可以这样做

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

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