Using typed value classes as identifiers is a common pattern in Scala. However, Mockito seems to have a problem with stubbing methods that take value classes as arguments. In the example below, the first stub with the actual value works just fine, and the second using an argument causes a NullPointerException to be thrown.
The only link to this I found this question , but the solution shown there does not work. Does anyone know this solution or workaround?
Versions: org.mockito: mockito-all: 1.10.19 and org.specs2: specs2_2.11: 2.4.15
import org.specs2.mutable.Specification
import org.specs2.matcher.Matchers
import org.specs2.mock.Mockito
case class ID[T](val id:Long) extends AnyVal
trait DAO[T]{
def get(id:ID[T]):T
}
class MockitoIDStubTest extends Specification with Mockito with Matchers{
"Mockito" should{
"properly stub with argument value" in {
val m = mock[DAO[String]
m.get(ID[String](1)).returns("abc")
m.get(ID[String](1)) must_== "abc"
}
"properly stub with argument matcher" in {
val m = mock[DAO[String]
m.get(any[ID[String]]).returns("abc")
m.get(ID[String](1)) must_== "abc"
}
}
}
[info] Mockito should
[info] +
[info]!
[error] NullPointerException: (MockitoIDStubTest.scala: 20)
[] MockitoIDStubTest $$ anonfun $1 $$ anonfun $apply $5 $$ anonfun $apply $6.apply(MockitoIDStubTest.scala: 20)