resource resolver mock in test not able to adapt query builder | Community
Skip to main content
Ravi_Joshi
Level 4
September 25, 2021

resource resolver mock in test not able to adapt query builder

  • September 25, 2021
  • 4 replies
  • 4606 views

Hi ,

 

I am facing one issue with sling model junit mock. I have created an resource resolver mock in the test file and in the model we are adapting resource resolver to query builder. while accessing through test case it is returning null value.

 

Model code snippet :

resourceResolver.adaptTo(QueryBuilder.class)

 

Resource resolver mock is created through AEM context object only.

 

Let me know your thoughts on the same.

 

Thanks,

Ravi Joshi

 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

4 replies

Sanjay_Bangar
Community Advisor
Community Advisor
September 25, 2021

Hi @ravi_joshi ,

                         In sling model which annotation have used for resourceresolver I mean @self  annotations.if it is @self annotation then it will gives you null pointer. You need to add @via resources then it will be not giving any error.

 

Kr,

Sanjay

 

Kr,

Sanjay

Ravi_Joshi
Level 4
September 25, 2021

Hi @sanjay_bangar ,

 

Thanks for replying. We are using @Inject annotation for resource resolver injection. I tried using Via annotation as well but no luck. Let me know if you have any other thought on the same.

 

Thanks,

Ravi Joshi

Sanjay_Bangar
Community Advisor
Community Advisor
September 26, 2021

Okay which adaption have you used for sling model . Can you please adapt  both slinghttpservlet and resource object.

 

 

Dinu_Arya
Level 6
September 25, 2021

Try @SlingObject or @OsgiService annotation for QueryBuilder instead of adapting it from resource resolver then try mocking QueryBuilder in test case

Ravi_Joshi
Level 4
September 26, 2021

Hi @dinu_arya ,

 

I have tested with both the Injections but still the same. Giving null for querybuilder when using @SlingObject or @OsgiService.

 

Thanks,

Ravi Joshi

Dinu_Arya
Level 6
September 26, 2021

Hi Ravi,

 

Null pointer is when running the test case or in sling model itself?

arunpatidar
Community Advisor
Community Advisor
September 26, 2021

Can you try something like below

 

@Mock
QueryBuilder mockQueryBuilder;

when
(mockResourceResolver.adaptTo(QueryBuilder.class)).thenReturn(mockQueryBuilder);

 

Arun Patidar
Vijayalakshmi_S
Level 10
September 27, 2021

Hi @ravi_joshi,

Please find below thread where I had a chance to share sample test class for Query Builder logic in Sling Servlet. 

https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/aem-servlet-junit-writing-which-using-querybuilder/td-p/375359

 

You can use the mock implementation (in @BeforeEach method) in your Sling Model Test case and continue per your Sling Model logic. 

If you face any issues, please do share your actual Sling Model class if possible.