我想知道并断言案例类是否已被访问?例如,在java值对象中,我可以在getter上断言以验证是否访问了值对象的实例变量。在 scala 中,我想在访问案例类字段时实现类似的事情。
case class Student(id:Int,name:String,department:String)
public def insertDataIntoTable(sc: Student = Student(1,"pspk","ap")) : Unit ={
val id = transform(sc.id)
val name = transform(sc.name)
val dept = transform(sc.department)
}
在上面的代码片段中,我想添加单元测试来验证每次执行插入DataIntoTable时访问ID,名称,部门字段1次。
在 mockito 的帮助下,我如何在单元测试中实现这一目标?
任何意见都非常感谢。谢谢
考虑将 Mockito.spy 与 Mockito.verifyZeroInteractions 结合使用,如下所示:
class HelloSpec extends FlatSpec with Matchers {
case class Student(id: Int, name: String, department: String)
"Student case class" should "not have interactions" in {
val student = Mockito.spy(Student(1, "Mario", "Starfleet Academy"))
student.department // access case class field
Mockito.verifyZeroInteractions(student)
}
}
这应该失败,并显示:
No interactions wanted here:
-> at example.HelloSpec.$anonfun$new$1(HelloSpec.scala:12)
But found this interaction on mock 'student':
-> at example.HelloSpec.$anonfun$new$1(HelloSpec.scala:11)
spy
可以检查与真实对象(如案例类(的交互,同时verifyZeroInteractions
可以按照锡上所说的进行操作。