MockitoValueClassSuite

MockitoValueClassSuite

将Scala的值类与Mockito Mocks(匹配器)一起使用会导致NullPointerException,请参见以下示例:

import org.scalatest.FunSuite
import org.scalatest.mock.MockitoSugar._
import org.mockito.{Matchers, Mockito}

class Id(val underlying: Int) extends AnyVal

class MockitoValueClassSuite extends FunSuite {

  trait Sample {
    def doIt(id: Id) : Int
  }

  test("Check value classes in scala with mockito") {
    val sampleMock = mock[Sample]

    val id = new Id(1)

    Mockito.when(sampleMock.doIt(Matchers.eq(id))).thenReturn(5)

    assert(sampleMock.doIt(id) == 5)
  }
}


结果是:

java.lang.NullPointerException was thrown.
java.lang.NullPointerException
    at net.gutefrage.service.user.service.MockitoValueClassSuite$$anonfun$1.apply$mcV$sp(MockitoValueClassSuite.scala:21)
    at net.gutefrage.service.user.service.MockitoValueClassSuite$$anonfun$1.apply(MockitoValueClassSuite.scala:16)
    at net.gutefrage.service.user.service.MockitoValueClassSuite$$anonfun$1.apply(MockitoValueClassSuite.scala:16)
    at org.scalatest.Transformer$$anonfun$apply$1.apply(Transformer.scala:22)


有什么提示可以在这里做什么?

最佳答案

假设NPE发生在Mockito上。我猜这是因为值类实际上是通过传递基本体来实现的,然后用静态方法替换了对它的方法调用,而Mockito则想在一个对象上调用equals,或类似的东西。如果那是原因,那么也许您可以在Scala中实现自己的匹配器以解决该问题。

07-26 03:25