JUnit Test Cases for Sling Models based on Delegation Pattern

gomatis80521865

24-12-2019

I am trying to write jUnit test cases for custom teaser component which extends the core Teaser component using the Delegation Pattern for Sling Models using "@Self @Via(type=ResourceSuperType.class)" as specified here: https://github.com/adobe/aem-core-wcm-components/wiki/Delegation-Pattern-for-Sling-Models
When I try to set the context (io.wcm.testing.mock.aem.junit5.AemContext) and adapt the context's request (I've tried resource as well) to the model I have created (like the "PageHeadline" from the example), I am getting a NullPointerException.

I am using AEM 6.5.2.0 and trying to run test cases in JUnit 5

junit models sling

Accepted Solutions (1)

Accepted Solutions (1)

Arun_Patidar

MVP

24-12-2019

Hi,

You need to use one more adaptable to adapt Teaser Component 

e.g.

@Model(adaptables = SlingHttpServletRequest.class, adapters = {Teaser.class, CustomTeaser.class}, resourceType = TeaserImpl.RESOURCE_TYPE)

 

Use CustomeTaeser to adapt to Junit test cases.

 

It will not cover 100% coverage but you will be able to write test cases for custom functionality.

Answers (4)

Answers (4)

Jörg_Hoh

Employee

27-06-2020

Anyway, next to the working solution this seems to be a short-coming of the mocking libraries. Can you create a minimal testcase (at best without any AEM dependency) and post it to the sling-developer list?

robertod4340573

26-06-2020

I have the same issue. I needed to declare the delegate proxy core component (Page in my case) as optional in my sling model as it is not resolved in the unit test (should not be optional in the real use case). Is a pity because my custom logic is simply a fallback of the core component one. I would like to have the object not null in my unit test so I will drop the Optional annotation for the field.

Jörg_Hoh

Employee

27-12-2019

have you registered the Sling model for the core teaser component as well to the context?

 

Jörg