dhamini-poornachandra / mockito

Automatically exported from code.google.com/p/mockito
0 stars 0 forks source link

ClassCastException #337

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
The method I want to test has a for loop with logic for each element in bList:

<code>
class A{

    void someMethod(){

     for(B b: bList){
        //some logic for b
        }
      }
   }</code>

I get an exception when executing following test:

     @RunWith(MockitoJUnitRunner.class)
     class ATest{

        @Mock
         private B b;

        @Mock
        private Map<Int, List<B>> bMap;

        @Mock(answer = Answers.RETURNS_DEEP_STUBS)
        private List<B> bList;

        @Spy
        @InjectMocks
        private C c;
        ....

        @Test
         public void test(){

          //this line executes fine
           when(bList.size()).thenReturn(1);

           //strangely this works fine
           when(bMap.get(any())).thenReturn(bList);

          //ClassCastException
           when(bList.get(0)).thenReturn(b); // or when(bList.get(anyInt())).thenReturn(b);

           c.methodIWantToTest();
        }

    }

The exception I get is:
<pre><code>java.lang.ClassCastException:
org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkA
roundCglibBug$$EnhancerByMockitoWithCGLIB$$ cannot be cast to xyz.B</code></pre>

I have searched for a solution and have come across some links: 
<http://code.google.com/p/mockito/issues/detail?id=251>
 and
<http://code.google.com/p/mockito/issues/detail?id=107>

Original issue reported on code.google.com by aces....@gmail.com on 25 Apr 2012 at 10:31

GoogleCodeExporter commented 8 years ago
I hit this my first run out with Mockito, switching from EasyMock.

HttpServletRequest req = mock(HttpServletRequest.class);

error:

java.lang.ClassCastException: 
$javax.servlet.http.HttpServletRequest$$EnhancerByMockitoWithCGLIB$$4720eeb0 
cannot be cast to org.mockito.cglib.proxy.Factory

version:

  mockito-core-1.8.5.jar

Original comment by p...@google.com on 29 Jun 2012 at 10:28

GoogleCodeExporter commented 8 years ago
I worked-around this by running tests from ant with no CLASSPATH previously set.

Original comment by p...@google.com on 29 Jun 2012 at 10:42

GoogleCodeExporter commented 8 years ago
@aces This is an issue with deep stubs. Besides the generic part of your list 
will be erased at runtime, so mockito could not even infer the type of the type 
that the list might hold.

@pmy I believe this might be an issue with your ant configuration. Ant might 
probably use another classloader for this CLASSPATH.

Original comment by brice.du...@gmail.com on 29 Jun 2012 at 11:29

GoogleCodeExporter commented 8 years ago

Original comment by brice.du...@gmail.com on 3 Sep 2012 at 10:00

GoogleCodeExporter commented 8 years ago

Original comment by brice.du...@gmail.com on 3 Sep 2012 at 10:11