Using typed value classes as IDs is a common pattern in Scala. However, it seems Mockito has an issue when stubbing methods that take value classes as arguments. In the example below, the first stub, with an actual value works just fine, but the second one, that uses an argument matcher throws NullPointerException.
The only reference to this I've found is this question but the solution shown there does not work. Anyone knows a solution to this, or a work-around?
Versions are: 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] + properly stub with argument value
[info] ! properly stub with argument matcher
[error] NullPointerException:(MockitoIDStubTest.scala:20)
[error] MockitoIDStubTest$$anonfun$1$$anonfun$apply$5$$anonfun$apply$6.apply( MockitoIDStubTest.scala:20)
It seems to work with scalamock and scalatest. I would still like to find a solution for Mockito tho, so I don't have to change a few hundred tests.
import org.scalatest._
import org.scalamock.scalatest.MockFactory
case class ID[T](val id:Long) extends AnyVal
trait DAO[T]{
def get(id:ID[T]):T
}
class ScalaMockIDStubTest extends WordSpec with MockFactory{
import language.postfixOps
"ScalaMock" should{
"properly stub with argument value" in {
val m = stub[DAO[String]
(m.get _) when(ID[String](1)) returns("abc")
assert( m.get(ID[String](1)) == "abc")
}
"properly stub with argument matcher" in {
val m = stub[DAO[String]
(m.get _) when(*) returns("abc")
assert( m.get(ID[String](1)) == "abc")
}
}
}
来源:https://stackoverflow.com/questions/28111015/mockito-stubbing-method-with-value-class-argument-fails-with-nullpointerexceptio