如何在Scala中断言验证案例类字段的访问?

时间:2019-04-09 08:42:35

标签: scala mockito scalatest

我想知道并断言是否访问了案例类? 例如,在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)

}

在上面的代码片段中,我想添加单元测试以验证每次执行insertDataIntoTable时访问id,name,department字段的时间为1。

借助嘲笑,我如何在单元测试中实现这一目标?

非常感谢任何投入。谢谢

1 个答案:

答案 0 :(得分:2)

考虑将Mockito.spyMockito.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可以检查与 real 对象(例如案例类)的交互,而verifyZeroInteractions可以按照提示进行操作。