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?
Solved! Go to Solution.
Views
Replies
Total Likes
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.
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.
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".