用原始类型模拟案例类

时间:2018-02-02 15:40:09

标签: scala unit-testing mockito scalatest

考虑以下类型结构:

trait HasId[T] {
    def id: T
}

case class Entity(id: Long) extends HasId[Long]

让我们说,我们想在某些测试中模拟实体类。

val entityMock = mock[Entity]
Mockito.when(entityMock.id).thenReturn(0)

在抛出NullPointerException(在第二行)中播放这样的测试结果,可能是因为包装原始类型的scala编译器行为(如果我们用String替换Long,测试执行正确)。

An exception or error caused a run to abort. 
java.lang.NullPointerException
at com.test.Entity$MockitoMock$1085095743.id(Unknown Source)
at com.test.Test.<init>(Test.scala:23)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at org.scalatest.tools.Runner$.genSuiteConfig(Runner.scala:1422)
at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$8(Runner.scala:1236)

此错误仅影响案例类,以及2.X版本中的mockito。

有没有任何已知的解决方案可以解决这个问题?

更新:问题出现在2.0.8-beta以上的版本中

1 个答案:

答案 0 :(得分:1)

这是我的测试类:

import org.mockito.Mockito._
import org.scalatest.mockito.MockitoSugar
import org.scalatest.FlatSpec

class StackOverflowTest extends FlatSpec with MockitoSugar {

  "Bla" should
    "fsg ll ll" in {
      val entityMock = mock[Entity]
      when(entityMock.id).thenReturn(0)
      foo(entityMock)
    }

  def foo(entity: Entity) = {
    entity.id == 0
  }

}

trait HasId[T] {
  def id: T
}

case class Entity(id: Long) extends HasId[Long]

这是我的sbt文件:

name := "scalaExperiments"

version := "0.1"

scalaVersion := "2.12.4"

libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.4" % Test

libraryDependencies += "org.mockito" % "mockito-all" % "2.0.2-beta" % Test

成功编译并通过。