我有一个 Sling 模型类,其中包含对我的服务的引用:
@OSGiService
PlanService planService;
该服务引用了 ResourceResolverFactory,以获取具有“管理员用户”的 ResourceResolver:
@Reference
private ResourceResolverFactory resolverFactory;
我正在编写一个单元测试来测试我的模型类上的 adaptTo。我正在尝试像这样注入对 PlanService 的引用:
@Rule
public final OsgiContext osgiContext = new OsgiContext();
osgiContext.registerInjectActivateService(new PlanServiceImpl());
但我不知道如何注入对 ResourceResolverFactory 的引用。
我试过这样:
osgiContext.registerInjectActivateService(new MockResourceResolverFactory());
但我得到这个错误:
org.apache.sling.testing.mock.osgi.NoScrMetadataException: No OSGi SCR metadata found in classpath at OSGI-INF/org.apache.sling.testing.resourceresolver.MockResourceResolverFactory.xml
我在文档和所有可用的模拟选项中找不到如何注入此服务并自动获取参考。任何帮助都会非常有帮助,谢谢!
编辑:感谢 Jérémie 的回答,ResourceResolverFactory 被注入到 PlanService 中。但是,我现在面临这个问题:
[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.
我尝试使用与 ResourceResolverFactory 相同的行:
osgiContext.registerService(PlanService.class, new PlanServiceImpl());
并且还要添加
MockModelAdapterFactory mockModelAdapterFactory = new MockModelAdapterFactory();
mockModelAdapterFactory.addModelsForPackage("c.r.o.c.m");
osgiContext.registerService(ModelAdapterFactory.class, mockModelAdapterFactory);
但它仍然是同样的问题......
编辑 2:用 SlingContext 而不是 OsgiContext 注册它解决了这个问题:
@Rule
public final SlingContext slingContext = new SlingContext(ResourceResolverType.RESOURCERESOLVER_MOCK);
@Mock
PlanService planServiceMock;
slingContext.registerService(PlanService.class, planServiceMock);