Mockito模拟课程的最终领域

时间:2020-07-10 12:19:58

标签: android kotlin mockito android-unit-testing

我正在尝试模拟学生班的最后一个领域

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

data class Marks(
    val subject1: String
)

这是我的考试班

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)

如何模拟标记字段

1 个答案:

答案 0 :(得分:1)

由于它是Kotlin类,您可以这样做

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

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