具有值类参数的Mockito存根方法因NullPointerException而失败

时间:2015-01-23 13:29:16

标签: scala nullpointerexception mockito specs2 value-class

使用类型化值类作为ID是Scala中的常见模式。但是,当存储将值类作为参数的方法时,Mockito似乎有一个问题。在下面的示例中,具有实际值的第一个存根工作得很好,但是第二个存根使用参数匹配器抛出NullPointerException。

我发现的唯一引用是this question,但是那里显示的解决方案不起作用。任何人都知道解决方案或解决方法吗?

版本为: org.mockito:mockito-all:1.10.19 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应该

     

[info] +带有参数值的正确存根

     

[info]!正确存根与参数匹配器

     

[error] NullPointerException:(MockitoIDStubTest.scala:20)

     

[error] MockitoIDStubTest $$ anonfun $ 1 $$ anonfun $ apply $ 5 $$ anonfun $ apply $ 6.apply(MockitoIDStubTest.scala:20)

1 个答案:

答案 0 :(得分:1)

它似乎适用于scalamockscalatest。我仍然想找到Mockito的解决方案,所以我不需要改变几百个测试。

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