Mockito stubbing method with value class argument not executed using NullPointerException

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)

+4
1

, scalamock scalatest. Mockito tho, .

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")
    }
  }
}
+1

All Articles