I am trying to write a junit test case and i am unable to mock the casting of jcr session to Jackrabbit session.
Here is my Code :
resolver = request.getResourceResolver();
session = resolver.adaptTo(Session.class);
jcrSession = (JackrabbitSession) session;
Below is my Junit :
PowerMockito.when((JackrabbitSession) session).thenReturn(jcrSession); // i am getting error at this point
when i am trying to do this, i am getting "java.lang.ClassCastException"
Below is the error:
java.lang.ClassCastException: $javax.jcr.Session$$EnhancerByMockitoWithCGLIB$$b9cd1700 cannot be cast to org.apache.jackrabbit.api.JackrabbitSession
I have mocked my session and resolver objects but still i am getting the error.
Please help me in Mocking this for my junit test.
Thanks & Regards,
Hi indrajithp11346880 ,
This is a very common error.Please see the below threads:
may I ask why do you need to have that cast at all? There should not be any need to do it.
I need to make some changes with the users in aem so i need the jackrabbit session which i need to get it from jcrSession session that why i need to cast it and the code is working fine but while writing my test case mocking that is cast is not working.
Thanks & Regards,
I have tried this and it is not working. I am also doing the similar implementation.
I have mocked both the jcrSession and Jackrabbit session.
can you please elaborate the below discussion little, i am not getting what he is trying to tell.
I would refactor the code in a way, that the cast to the JackrabbitSession plus all dependent functionality is separated in a dedicated method, and then stub this method with Mockito completely.
(Also I would recommend to use SlingContext, so you don't need to mock resources and nodes. See  for a sample.)
Hi @indrajithp11346 ,
You can try like below
when --> resolver.adaptTo(Session.class)).thenReturn(jackrabbitSession object) . @Mock JackrabbitSession jackrabbitSession ; and return jackrabbitSession object in thenReturn method.
If you try above you won't get cast exception