0

I've been doing some work with sling models for a project and in the process created a couple of custom injectors. Everything seems to work great when implemented (used in AEM). However, when I'm testing the custom injectors are not getting run.

Here's an example of what I currently have set up

In MyModel

@Inheritable
@CustomAnnotation("foo")
private String _foo

In test (tests using wcm.io mocking Libraries)

@Rule
AemContext context = new AemContext(ResourceResolverType.RESOURCERESOLVER_MOCK);

//required by the injector
@Mock
InheritanceService _inheritanceService;

@Mock
InheritableInjector _inheritanceInjector;

@Before
public void setup() {
    context.registerService(InheritanceService.class, _inheritanceService);
    context.registerService(InheritableInjector.class, _inheritanceInjector);

    context.addModelsForPackage("com.package.example.models");

    //use this resource in tests to adaptTo(MyModel.class)
    _resource = context.load().json("myJson.json", "/myPath");
}

... tests

The tests compile and run, but the Injector isn't being executed. I know it's registered because when I don't have the Injector's dependent services registered in the context I get an error. When I debug through it, none of the breakpoints are hit. I'm wondering if I need to also register the "Inheritable" annotation somewhere or if anyone just has any general information on how I can get the custom injector to execute.

thank you

Connor Low
  • 5,900
  • 3
  • 31
  • 52
Brodie
  • 8,399
  • 8
  • 35
  • 55

1 Answers1

1

I was able to figure out my error. So the important thing to remember about Sling Model Injectors is that they are just OSGI services (something I completely let myself get away from).

So just treating them like normal services and then remembering to annotate the Injector with @InjectMocks was what I needed to do in order to fix the error.

The following now works great.

@Mock
InheritanceService _inheritanceService; //injector dependency

@InjectMocks
InheritanceInjector _inheritanceInjector;

@Before
public void setup() {
    context.registerService(InheritanceService.class, _inheritanceService);
    context.registerService(InheritableInjector.class, _inheritanceInjector);
}

hopefully that helps anyone that might run into the issue. If anyone can make this answer better please feel free to reply/edit.

Brodie
  • 8,399
  • 8
  • 35
  • 55
  • Hi Brodie, I came across a similar issue you faced with testing custom injectors. My case is not quite the same as yours since the custom injector wasn't implemented by me, but the @AemObject from ACS AEM Commons. It would be interesting to know your thoughts about it, perhaps you can help me understand what is wrong with the code shared here: https://stackoverflow.com/questions/46993268/sling-model-unit-tests-mock-currentpage-in-slinghttpservletrequest Thanks in advance for sharing your findings. – Jose Berciano Oct 31 '17 at 16:52