模拟具有原始类型的案例类

编程入门 行业动态 更新时间:2024-10-26 02:31:43
本文介绍了模拟具有原始类型的案例类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑以下类型结构:

trait HasId[T] { def id: T } case class Entity(id: Long) extends HasId[Long]

比方说,我们想在某些测试中模拟Entity类.

Let's say, we want to mock Entity class in some test.

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

播放此类测试结果会引发NullPointerException(第二行),这可能是由于Scala编译器的行为带有包装原始类型(如果将Long替换为String,则测试可以正确执行).

Playing such test results in throwing NullPointerException (in second line), probably because of scala compiler behaviour with wrapping primitive types (if we replace Long with String, test executes correctly).

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版本中的模拟.

This error affects only case classes, and mockito in 2.X versions.

有没有已知的解决方案来解决此问题?

Is there any known solution to handle this issue?

更新:在2.0.8-beta之前的版本中出现问题

UPDATE: problem occurs in versions newer than 2.0.8-beta

推荐答案

这是我的测试课程:

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

编译并成功通过.

更多推荐

模拟具有原始类型的案例类

本文发布于:2023-10-31 05:48:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545192.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原始   案例   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!