Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

Mock Casting of jcr Session to Jackrabbit Session - (JackrabbitSession) session

indrajithp11346
Level 2
Level 2

Hi All,

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 :

     @Mock

    Session session;

     @Mock

    ResourceResolver resolver;

    @Mock

    JackrabbitSession jcrSession;

PowerMockito.when(request.getResourceResolver()).thenReturn(resolver);

PowerMockito.when(resolver.adaptTo(Session.class)).thenReturn(session);

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,

Indrajith

5 Replies
Jörg_Hoh
Employee
Employee

Hi,

may I ask why do you need to have that cast at all? There should not be any need to do it.

Jörg

indrajithp11346
Level 2
Level 2

Hi,

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,

Indrajith

indrajithp11346
Level 2
Level 2

Hi,

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.

https://stackoverflow.com/questions/28462611/mockito-classcastexception-a-mock-cannot-be-c ast

Jörg_Hoh
Employee
Employee

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 [1] for a sample.)

[1] https://cqdump.wordpress.com/2019/01/17/writing-unittests-for-aem-part-3-mocking-resources/