Expand my Community achievements bar.

SOLVED

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

Avatar

Level 1

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:

1 Accepted Solution

Avatar

Correct answer by
Level 10

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

View solution in original post

3 Replies

Avatar

Level 1

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);

Avatar

Correct answer by
Level 10

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

Avatar

Level 1

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