Scala Value类和Mockito Matchers不能一起玩

时间:2013-11-14 09:54:53

标签: scala mockito

在Mockito Mocks(Matchers)中使用Scala的值类会导致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)

任何提示可以在这里做什么?

2 个答案:

答案 0 :(得分:4)

假设NPE发生在Mockito.when-line上我猜它是因为值类实现为实际传递基元然后用静态方法替换方法调用,而Mockito想调用equals on一个对象,或类似的东西。如果这就是原因,那么你可以在Scala中实现自己的匹配器来解决它。

答案 1 :(得分:1)

在你的情况下,你必须使用这样的东西:

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

Mockito.doReturn(5).when(sampleMock).doIt(Id(Matchers.eq(id)))