Reputation: 827
I wanted to know and assert whether case class has been accessed or not ? For instance in java value objects i can assert on getters to verify whether the instance variables of value objects were accessed or not . In scala i want to achieve similar thing while accessing case class fields.
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)
}
In the above code snippet i would like to add unit-test to verify id , name , department fields were accessed 1 time every time insertDataIntoTable is executed.
With the help of mockito how can i achieve that in unit-tests ?
Any inputs are much appreciated. Thank you
Upvotes: 0
Views: 1146
Reputation: 48420
Consider using Mockito.spy in combination with Mockito.verifyZeroInteractions like so:
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)
}
}
This should fail with:
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
enables inspecting interactions with real objects such as case classes, whilst verifyZeroInteractions
does what it says on the tin.
Upvotes: 2