Expand my Community achievements bar.

SOLVED

AEM - JUnit @Inject annotation

Avatar

Level 2

Hi all,
I’am facing an issue regarding the handling of the @inject annotation with AEM-Junit test scenario.
Here an example of the issue:
Model Class:

 

@Model(adaptables = {SlingHttpServletRequest.class}, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SimpleModel  {

    @inject
    private Resource currentResource;

    public Resource getCurrentResource(){
       return currentResource;
    }

}

 

Test Class:

 

@ExtendWith({AemContextExtension.class, MockitoExtension.class})
public class SimpleModelTest{

    private AemContext context = new AemContext();
    private SimpleModel simpleModel;

    @BeforeEach
    public void setup() throws Exception {
        context.addModelsForClasses(SimpleModel.class);
        context.load().json("SimpleModelTest.json", "/content/myproject/us");
    }

    @test
    void testResource() {
        context.currentResource("/content/myproject/us/jcr:content/simple-component");
        simpleModel = context.request().adaptTo(SimpleModel.class);
        assertNotNull(simpleModel.getCurrentResource());
    }

}

 

The test fails since simpleModel.getCurrentResource() gives me a null resource.
If I change the @inject annotation in the SimpleModel class with @SlingObject the test doesn't fail, but I don’t want to change every annotation with SlingObject or the similar one.

Could you help me to solve this issue?

1 Accepted Solution

Avatar

Correct answer by
Employee Advisor

My thinking is that it should not need these statements. Also a page injector is not default (IIRC it is a wcm.io feature).

 

Have you tried to switch to this:

@Model(adaptables = {Resource.class}, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SimpleModel  {
...
}

If you don't need any information from the request (e.g. a parameter) this is much more flexible.

View solution in original post

23 Replies

Avatar

Correct answer by
Employee Advisor

My thinking is that it should not need these statements. Also a page injector is not default (IIRC it is a wcm.io feature).

 

Have you tried to switch to this:

@Model(adaptables = {Resource.class}, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SimpleModel  {
...
}

If you don't need any information from the request (e.g. a parameter) this is much more flexible.

Avatar

Level 3

Hi... It is not working in case of 

@inject
@source("script-bindings")
Page currentPage;

 

Could you please help me that how can i mock this?

Avatar

Employee Advisor

You should be able to remove the @source annotation, it won't change the result. And of course the resource must point to a "cq:page" resource with a "jcr:content" child resource with the nodetype "cq:pageContent".