Mike
Mike

Reputation: 857

How to resolve ClassCastException using Mockito/PowerMockito

I am in a situation where I need to Mock two static methods using PowerMocklito. It gives me a mocked object for the first line of code but then the same method is called again but this time it is returning a different object and this throws ClassCastException.

Method Under test

ESignatureJaxBContextFactory context = (ESignatureJaxBContextFactory) AppContext.getBean("jaxbContextFactory");
/// More code
DocusignRESTClient client = (DocusignRESTClient) AppContext.getBean("restServiceClient");

Junit

private ESignatureJaxBContextFactory eSignatureJaxBContextFactory;
eSignatureJaxBContextFactory = mock( ESignatureJaxBContextFactory.class );

PowerMockito.when( AppContext.getBean( any( String.class ) ) ).thenReturn( eSignatureJaxBContextFactory );

So above line of code returns me mock context, but I get an exception when it tries to fetch client. How can I test this?

Thanks in advance

Upvotes: 1

Views: 863

Answers (1)

Sergii Bishyr
Sergii Bishyr

Reputation: 8641

The problem is that you are mocking AppContext.getBean for any( String.class ) Try this:

PowerMockito.when(AppContext.getBean("jaxbContextFactory"))
            .thenReturn(eSignatureJaxBContextFactory);
PowerMockito.when(AppContext.getBean("restServiceClient"))
            .thenReturn(docusignRESTClient);

In this case when AppContext.getBean is invoked with parameter "jaxbContextFactory" it will return eSignatureJaxBContextFactory but not for any other parameters. So you also need to mock invocation with parameter "restServiceClient".

Other way of testing it is to provide a set of consecutive return values:

PowerMockito.when(AppContext.getBean(any(String.class)))
            .thenReturn(eSignatureJaxBContextFactory, docusignRESTClient);

In this case you still mock any invocation of AppContext.getBean with any String value as parameter, but are telling mockito to return eSignatureJaxBContextFactory on first invocation and to return docusignRESTClient on second and any further invocations.

Upvotes: 1

Related Questions