I\'m using mockito with scalatest. I have following problem when using matcher with value class.
import org.scalat
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
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])
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 :-)
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)
My class also extended AnyVal
case class ApplicationKey(value: String) extends AnyVal {
override def toString: String = value
}
and this worked for me:
when(waterfallLogicEventWriter.writeAuctionEvents(
Eq(waterfallRequest.auctionId), Eq(waterfallRequest.ip),
ApplicationKey(any[String]),
any()).thenReturn(waterfallEvents)