Scala Value 类和 Mockito Matchers 不一起玩 [英] Scala Value classes and Mockito Matchers don't play together

查看:44
本文介绍了Scala Value 类和 Mockito Matchers 不一起玩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将 Scala 的值类与 Mockito Mocks (Matchers) 结合使用会导致 NullPointerException,请参阅此示例:

Using Scala's value classes with Mockito Mocks (Matchers) results in a NullPointerException, see this example:

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)

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

Any hints what can be done here?

推荐答案

假设 NPE 发生在 Mockito.when 行上,我猜这是因为值类被实现为实际传递原语然后替换方法使用静态方法调用它,而 Mockito 想在对象上调用 equals 或类似的东西.如果这是原因,那么也许您可以在 Scala 中实现自己的匹配器来解决它.

Assuming that the NPE happens on the Mockito.when-line I'd guess it is because the value classes are implemented as actually passing around the primitive and then replacing method calls on it with static methods while Mockito wants to call equals on an object, or something like that. If that is the reason then maybe you could implement your own matcher in Scala to work around it.

这篇关于Scala Value 类和 Mockito Matchers 不一起玩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆