AEM Mocks - mock context's resources null after first test

tomp10987048

17-09-2019

Hello,

I'm new to AEM and AEM Mocks, and trying to implement unit testing in a small AEM 6.5 project. However I'm having issues with the AemContext.

I have 3 test cases to test an OSGi service, the service itself is basically a POJO that takes a page (com.day.cq.wcm.api.Page) as a parameter.

My problem is that only the first test case that executes can retrieve pages from the mock context. The other two test cases, even when using the exact same method of grabbing pages, result in a NullPointerException on the line that gets the page from the context.

I've also tried using context.currentResource("/content/en/eventPage1").adaptTo(Page.class); and again this works only in the first test method.

Here is my test file:

And my test JSON:

Accepted Solutions (1)

Accepted Solutions (1)

Theo_Pendle

MVP

19-09-2019

Hi Tom,

The reason for this is that you are persisting the state of your context from method to method. This is causing conflicts in the context's ResourceResolver adapter cache and resulting in it not being able to adapt to Page.class more than once.

The solution is to simply remove the following line from your test:

@TestInstance(TestInstance.Lifecycle.PER_CLASS)

Hope it helps

Answers (2)

Answers (2)

tomp10987048

19-09-2019

Thank you! I was told by the compiler that I needed a test instance lifecycle declared, but after deleting it, it is running as intended.

Thank again

tomp10987048

19-09-2019

I've also tried getting the resources through the resource resolver from the context with the same results:

The context seems to lose all of the json after one method.

Resource resource = resourceResolver.getResource("/content/en/eventPage1");
Page eventPage1 = resource.adaptTo(Page.class);