Sling Models adaptTo is returning null | Community
Skip to main content
Level 2
July 10, 2023
Solved

Sling Models adaptTo is returning null

  • July 10, 2023
  • 3 replies
  • 2463 views

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

 

 

 

Best answer by ayush-anand

@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 

3 replies

DPrakashRaj
Community Advisor
Community Advisor
July 11, 2023

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

ayush-anand
ayush-anandAccepted solution
Level 4
July 11, 2023

@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 

DustyAuthor
Level 2
July 12, 2023

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.

Level 2
January 14, 2025

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.

Community Advisor
July 11, 2023

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.