I'm trying to mock a method that returns an instance of a value class (extends AnyVal
)
I'm getting some weird error message, which I understand (because of value class erasure) but I'm surprised Mockito doesn't cope with that.
My class:
case class MyValueClass(value: String) extends AnyVal
The function I want to mock:
trait ToMock {
def something(someParams: String): MyValueClass
}
And the mock:
val theMock = mock[ToMock]
val returned = MyValueClass("test")
when(theMock.something("test")).thenReturn(returned)
This code generates the following error:
MyValueClass cannot be returned by something()
something() should return String
But of course, if I make it return a String, it doesn't compile anymore...
If I remove extends AnyVal
, of course it works fine.
OK, I found an answer that works.
I need to use the older mockito style of doReturn
doReturn(returned.value).when(theMock).something("test")
Because it's not type-safe, it works. Not fully satisfactory though, as I give up type safety.