获取对 (Mock)ResourceResolverFactory 的引用

Get reference to (Mock)ResourceResolverFactory

我有一个 Sling 模型 class 包含对我的服务的引用:

@OSGiService
PlanService planService;

此服务引用了 ResourceResolverFactory,以获取具有 "admin user":

的 ResourceResolver
@Reference
private ResourceResolverFactory resolverFactory;

我正在编写单元测试以在我的模型上测试 adaptTo class。我正在尝试像这样注入对 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);

试试这个:

osgiContext.registerService(ResourceResolverFactory.class, new MockResourceResolverFactory());

OsgiContext 的 Javadoc 是 here

在测试之前尝试清理和构建您的项目。

例如,

gradlew clean build test

我遇到了同样的问题,我使用 https://sling.apache.org/documentation/development/osgi-mock.html 上的指南并按以下方式制作。现在对我有用了:

    BundleContext bundleContext = MockOsgi.newBundleContext();
    //register the service
    bundleContext.registerService(OtherService.class.getName(), new OtherService(), null);
    // get service instance
    ServiceReference ref = bundleContext.getServiceReference(OtherService.class.getName());
    OtherService service = (OtherService)bundleContext.getService(ref);