Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.

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

Avatar

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

6 Replies

Avatar

Employee Advisor

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

Avatar

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

Avatar

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

Avatar

Employee Advisor

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/

Avatar

Level 4

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