Mockito matchers, scala value class and NullPointerException

痴心易碎 提交于 2019-11-29 01:13:51

The proper solution is:

case class StringValue(val text: String) extends AnyVal
case class LongValue(val value: Long) extends AnyVal

val eqFirst: StringValue = StringValue(org.mockito.Matchers.eq("first"))
val anySecond: StringValue = StringValue(org.mockito.Matchers.any[String])

val eqFirst: LongValue = LongValue(org.mockito.Matchers.eq(1L))
val anySecond: LongValue = LongValue(org.mockito.Matchers.any[Long])

I found solution:

val anyFirstId: FirstId = any[String].asInstanceOf[FirstId]
val eqSecondId: SecondId = org.mockito.Matchers.eq[String](secondId.value).asInstanceOf[SecondId]
given(mockedClass.someMethods(anyFirstId, eqSecondId)).willReturn(3)

This works for all kinds of extends AnyVal value classes and doesn't need special matchers either:

    given(mockedClass.someMethods(FirstId(anyString), SecondId(org.mockito.Matchers.eq(secondId.value)))).willReturn(3)

The newest version of mockito-scala (0.0.9) supports this out of the box, you can do something like

when(myObj.myMethod(anyVal[MyValueClass]) thenReturn "something"

myObj.myMethod(MyValueClass(456)) shouldBe "something"

verify(myObj).myMethod(eqToVal[MyValueClass](456))

Disclaimer: I'm a developer of that library

If you have shapeless in your dependencies you could consider my little helper method: https://gist.github.com/Fristi/bbc9d0e04557278f8d19976188a0b733

Instead of writing

UserId(is(context.userId.value))

You can write

isAnyVal(context.userId)

Which is a bit more convenient :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!