I'm trying to write unit tests for an AEM Sling Model, but my test is failing. Here's the test I tried:
@RunWith(MockitoJUnitRunner.class)
public class ArticleContentModelTest {
@Rule
public AemContext context = new AemContext();
private ArticleContentModel articleContentModel;
@Before
public void setUp() {
context.create().resource("/content/article", "title", "Sample Article", "body", "This is a sample article body.");
articleContentModel = context.request().adaptTo(ArticleContentModel.class);
}
@test
public void testGetTitle() {
assertEquals("Sample Article", articleContentModel.getTitle());
}
@test
public void testGetBody() {
assertEquals("This is a sample article body.", articleContentModel.getBody());
}
}
I am getting a NullPointerException when trying to assert the title and body in the tests. I have checked that the resource exists, and the ArticleContentModel should have been adapted correctly, but something is wrong.
Solved! Go to Solution.
Views
Replies
Total Likes
Hi @AadhiraRa,
I think the problem is that your Sling model wasn’t properly registered in the test context. Even if the resource is set properly - the adaptation will silently fail.
Try this:
context.addModelsForClasses(ArticleContentModel.class); // Registers the Sling model
Resource resource = context.resourceResolver().getResource("/content/article");
articleContentModel = resource.adaptTo(ArticleContentModel.class); // Resource-based adaptation
Hope that help!
Hello @AadhiraRa
Problem seems to be here :
articleContentModel = context.request().adaptTo(ArticleContentModel.class);
To fix it, make sure the request is pointing to the correct resource(setResource) before calling adaptTo.
@Before
public void setUp() {
context.create().resource("/content/article", "title", "Test", "body", "test body");
Resource resource = context.resourceResolver().getResource("/content/article");
context.request().setResource(resource);
articleContentModel = context.request().adaptTo(ArticleContentModel.class);
}
Reference :
https://sling.apache.org/documentation/development/sling-mock.html#slinghttpservletrequest-1
Views
Replies
Total Likes
@muskaanchandwani Thanks for your input! I actually tried the exact approach you suggested - setting the resource explicitly on the request as you mentioned above. Unfortunately, this still results in articleContentModel being null, and the test fails with a NullPointerException.
Views
Replies
Total Likes
Hi @AadhiraRa,
I think the problem is that your Sling model wasn’t properly registered in the test context. Even if the resource is set properly - the adaptation will silently fail.
Try this:
context.addModelsForClasses(ArticleContentModel.class); // Registers the Sling model
Resource resource = context.resourceResolver().getResource("/content/article");
articleContentModel = resource.adaptTo(ArticleContentModel.class); // Resource-based adaptation
Hope that help!
Worked. Thanks!
Views
Replies
Total Likes