I have a Sling model class containing a reference to a service of mine:
@OSGiService
PlanService planService;
This service has a reference to ResourceResolverFactory, to get a ResourceResolver with the "admin user":
@Reference
private ResourceResolverFactory resolverFactory;
I'm writing a unit test to test adaptTo on my model class. I'm trying to inject the reference to PlanService like this:
@Rule
public final OsgiContext osgiContext = new OsgiContext();
osgiContext.registerInjectActivateService(new PlanServiceImpl());
But I don't know how to inject the reference to the ResourceResolverFactory.
I've tried like this:
osgiContext.registerInjectActivateService(new MockResourceResolverFactory());
But I get this error:
org.apache.sling.testing.mock.osgi.NoScrMetadataException: No OSGi SCR metadata found in classpath at OSGI-INF/org.apache.sling.testing.resourceresolver.MockResourceResolverFactory.xml
I couldn't find in the documentation and among all the mocking options available how to inject this service and get the reference automatically. Any help would be very helpful, thank you!
EDIT: Thanks to Jérémie's answer, the ResourceResolverFactory is injected in the PlanService. However, I'm now facing this issue:
[main] WARN org.apache.sling.models.impl.ModelAdapterFactory - Required properties [c.r.o.c.s.j.PlanService c.r.o.c.m.Plan.planService] on model class class c.r.o.c.m.Plan were not able to be injected.
I've tried to use the same line than for the ResourceResolverFactory:
osgiContext.registerService(PlanService.class, new PlanServiceImpl());
And also to add
MockModelAdapterFactory mockModelAdapterFactory = new MockModelAdapterFactory();
mockModelAdapterFactory.addModelsForPackage("c.r.o.c.m");
osgiContext.registerService(ModelAdapterFactory.class, mockModelAdapterFactory);
But it's still the same problem...
EDIT 2: registering it with SlingContext instead of OsgiContext fixed the issue:
@Rule
public final SlingContext slingContext = new SlingContext(ResourceResolverType.RESOURCERESOLVER_MOCK);
@Mock
PlanService planServiceMock;
slingContext.registerService(PlanService.class, planServiceMock);
Try this:
osgiContext.registerService(ResourceResolverFactory.class, new MockResourceResolverFactory());
The Javadoc of the OsgiContext
is here