mockito-scala icon indicating copy to clipboard operation
mockito-scala copied to clipboard

Mockito generates mock with incorrect subtyping if trait extends abstract class

Open YulawOne opened this issue 4 years ago • 4 comments

Java: 11 Scala: 2.13.1 Mockito: 3.3.3 Mockito Scala: 1.13.10

abstract class Foo
trait Bar extends Foo

val bar = mock[Bar]
val foo: Foo = bar // or bar.asInstanceOf[Foo]

fails with:

class Bar$MockitoMock$419587131 cannot be cast to class Foo (Bar$MockitoMock$419587131 and Foo are in unnamed module of loader 'app')
java.lang.ClassCastException: class Bar$MockitoMock$419587131 cannot be cast to class Foo (Bar$MockitoMock$419587131 and Foo are in unnamed module of loader 'app')

YulawOne avatar Apr 28 '20 18:04 YulawOne

@YulawOne hmm, it looks like a bug on the Scala compiler, I'll check with them and see if there is a solution for this

ultrasecreth avatar May 03 '20 00:05 ultrasecreth

As the issue in the scala compiler says, it's a limitation on the Java type system, which is what Mockito uses under the hood, I'll try to see if there is a way to overcome this limitation, but I'm not really sure it will be possible in the short term

ultrasecreth avatar May 04 '20 16:05 ultrasecreth

I also though it something specific to way how traits are compiled. I have found workaround in my codebase, but will be great if this issue could be solved in future

YulawOne avatar May 22 '20 11:05 YulawOne

I can't promise anything as the mock generator uses Java reflection which is completely oblivious of this particular case, as it's illegal in the Java type system. I'll keep trying ideas, but most probably unless I re-write the core of mockito again in Scala, I don't think it will be feasible.

ultrasecreth avatar May 22 '20 19:05 ultrasecreth