Skip to content
Advertisement

“resource.adaptTo” NullPointer Unit test AEM Sling Model Java

I’m doing a pretty basic Unit test for Sling Model in AEM, so, when I run the test I get the following error:

[ERROR] CtaModelTest.testGetText:36 NullPointer

This is my Java code, the Model is a very basic Sling AEM Model, I’m using the @ModelAnnotation as follow:

JavaScript
JavaScript

Can anyone help me to fix it?

Advertisement

Answer

It seems that resource.adaptTo(CtaModel.class) returned null. The problem is, that adaptTo(…) returns null very silently, if anything fails. Therefore the SlingMocks documentation recommends ModelFactory.createModel(...) instead of adaptTo(...) for SlingModels.

https://sling.apache.org/documentation/development/sling-mock.html#model-instantiation

JavaScript

If you doing this, the ModelFactory will log error-details, why the Sling model couldn’t be created. So you know, what the problem is, and you don’t need to guess.

Advertisement