mockito: java.lang.ClassCastException with generic types

Hi,

I’ve tried this:

@Test
public void test() {
    given(testCollectionSourceProvider.getCollection(new ArrayList<Integer>())).willReturn(new ArrayList<>());
}

static class TestCollectionSourceProvider {
    <T extends Collection<E>, E> T getCollection(T collection) {
        return collection;
    }
}

But I’ve got an Exception with a very confusing message in Idea 2017.1.5 and Eclipse Neon.3:

java.lang.ClassCastException: java.util.LinkedList cannot be cast to java.util.ArrayList
	at com.example.demo.FailingTestWithCollectionsTest.test(FailingTestWithCollectionsTest.java:24)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

But it works from Maven.

If I cast it manually, it works from IDEs:

given((List<Integer>) testCollectionSourceProvider.getCollection(new ArrayList<Integer>())).willReturn(new ArrayList<>());

Java versions:

  1. machine

java version “1.8.0_144” Java™ SE Runtime Environment (build 1.8.0_144-b01) Java HotSpot™ 64-Bit Server VM (build 25.144-b01, mixed mode)

IntelliJ IDEA 2017.1.5 Build #IC-171.4694.70, built on July 4, 2017 JRE: 1.8.0_112-release-736-b21 amd64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Windows 10 10.0

Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-03T21:39:06+02:00) Maven home: C:\Maven Java version: 1.8.0_131, vendor: Oracle Corporation Java home: C:\Program Files\Java\jdk1.8\jre Default locale: en_US, platform encoding: Cp1252 OS name: “windows 10”, version: “10.0”, arch: “amd64”, family: “windows”

  1. machine

java version “1.8.0_141” Java™ SE Runtime Environment (build 1.8.0_141-b01) Java HotSpot™ 64-Bit Server VM (build 25.141-b01, mixed mode)

Platform: Eclipse Neon.3 (4.6.3) Version: 3.9.0.RELEASE Build Id: 201707061903 Windows 7

Please check it: https://github.com/shark300/ClassNotFoundException-in-Mockito

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Comments: 15 (8 by maintainers)

Commits related to this issue

Most upvoted comments

Yes I can reproduce this issue with the Eclipse compiler in IntelliJ. To enable the Eclipse compiler File -> Settings -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Use compiler. Select Eclipse. Then recompile the test added in #1219 (ctrl + shift + F9) and then run the test.