Expand my Community achievements bar.

Enhance your AEM Assets & Boost Your Development: [AEM Gems | June 19, 2024] Improving the Developer Experience with New APIs and Events
SOLVED

How to Mock the NodeIterator for JUnit5 testcases ?

Avatar

Level 2

I have the below snippet of code from service class for which i am trying to write a JUnit testcase.

I wanted to stub my NodeIterator, I have tried different approaches to do it but it never returns the mockobject, instead always returns the actual object, am I missing something here ?

The Size of the Node Iterator is always 0 too.

Snippet from Service Class:

 

 

Session session = userResourceResolver.adaptTo(Session.class);
QueryManager queryManager = session.getWorkspace().getQueryManager();
Query query = queryManager.createQuery(statement, Query.JCR_SQL2);
QueryResult queryResult = query.execute();
NodeIterator nodeIter = queryResult.getNodes();
LOG.debug("size is {}", nodeIter.getSize());
nodeIter.forEachRemaining((item) -> {
   getUserNodeProperties(excludedGroups, userResourceResolver, session, item);
});

 

 

Approaches done so far for Testcases to mock the NodeIterator in Junit5:

 

Approach 1:

 

lenient().when(mockResourceResolverFactory.getResourceResolver(anyMap())).thenReturn(mockResourceResolver);
lenient().when(mockResourceResolver.adaptTo(Session.class)).thenReturn(mockSession);
lenient().when(mockSession.getWorkspace()).thenReturn(mockWorkspace);
lenient().when(mockWorkspace.getQueryManager()).thenReturn(mockQuerymanager);
lenient().when(mockQuerymanager.createQuery("dummy", Query.JCR_SQL2)).thenReturn(mockQuery);
lenient().when(mockQuery.execute()).thenReturn(mockresult);
lenient().when(mockresult.getNodes()).thenReturn(mockNodeItr);    lenient().when(mockNodeItr.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false);	 lenient().when(mockNodeItr.nextNode()).thenReturn(userOneNode).thenReturn(userTwoNode).thenReturn(null);

 

 

Approach 2:

 

doReturn(mockNodeItr).when(mockresult).getNodes();
doReturn(true,true,false).when(mockNodeItr).hasNext();
doReturn(userOneNode,userTwoNode,null).when(mockNodeItr).next();

 

 

Is there any other way to mock it ? Am I missing something in here, please let me know

 

Thanks.

 

@arunpatidar @VeenaVikraman @Albin_Issac 

 

Thank you.

 

Topics

Topics help categorize Community content and increase your ability to discover relevant content.

1 Accepted Solution

Avatar

Correct answer by
Community Advisor
2 Replies

Avatar

Correct answer by
Community Advisor

Avatar

Level 2

Thanks a lot for these samples. Helped me resolve the issue.