Expand my Community achievements bar.

SOLVED

Sling Models adaptTo is returning null

Avatar

Level 1

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

 

 

 

1 Accepted Solution

Avatar

Correct answer by
Level 4

@Dusty1186 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 

View solution in original post

4 Replies

Avatar

Community Advisor

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

Avatar

Correct answer by
Level 4

@Dusty1186 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 

Avatar

Level 1

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.

Avatar

Level 6

Hi @Dusty1186

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.