Skip to main content
Level 2
Jul 10, 2023 9:06 PM UTC
Solved

Sling Models adaptTo is returning null

Hi all, I'm having trouble with this line in my unit test returning null.  I can't figure out why the adaptTo is returning null.  Let me know if you have any idea as to what I may be doing wrong.  Thank you!

 

removed

 

 

I've tried to include the relevant code below.

My class

 

removed

 

 

And the relevant code from the unit test:

 

removed

 

 

 

ayush-anand
ayush-anandAccepted solution
Level 4
Jul 11, 2023 4:55 AM UTC

@dusty adaptTo(...) returns null if anything fails in the Model class without showing any error. You can try using ModelFactory.createModel(...) instead of adaptTo(...) for SlingModels which would log all the error details and would help you in debugging the code further.

 

ReferenceModel referenceModel = context.getService(ModelFactory.class).createModel(request, ReferenceModel.class);

Hope this helps.

 

Regards,

Ayush 

5 replies

DPrakashRaj
Community Advisor
Community Advisor
Jul 11, 2023 1:16 AM UTC

Doesn’t you should either work with resource.adaptTo() or resourceresolver.adapto() instead of request.adaptTo() ?

please check this https://wcm.io/testing/aem-mock/usage.html

Translate
ayush-anand
ayush-anandAccepted solution
Level 4
Jul 11, 2023 4:55 AM UTC

@dusty adaptTo(...) returns null if anything fails in the Model class without showing any error. You can try using ModelFactory.createModel(...) instead of adaptTo(...) for SlingModels which would log all the error details and would help you in debugging the code further.

 

ReferenceModel referenceModel = context.getService(ModelFactory.class).createModel(request, ReferenceModel.class);

Hope this helps.

 

Regards,

Ayush 

Translate
DustyAuthor
Level 2
Jul 12, 2023 12:38 PM UTC

This was it.  I discovered that in the init of my model class there was a property that would return null in the unit test, as I was assigning a value to it after the adaptTo.  This would cause the adaptTo in the unit test to fail, even though everything as far as the model goes was working correctly in the application.

 

Thanks.

Translate
Level 2
Jan 14, 2025 7:58 AM UTC

I also faced same issue and on further debugging I found one of the property inside init() which was coming from another model was giving NPE and thus

request.adaptTo(MyModel.class)

was giving null. After updating code for that property issue was resolved.

Translate
salamswapnil
Community Advisor
Community Advisor
Jul 11, 2023 6:25 AM UTC

Hi @dusty

The CONTENT_PATH where you are loading your json has to be absolute path and not relative. I think json is not loading properly.

Please make CONTENT_PATH absolute and try.

Translate