3

我有一个 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);
4

3 回答 3

2

尝试这个:

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

的 JavadocOsgiContext这里

于 2016-03-18T16:14:30.887 回答
1

我遇到了同样的问题,而不是我使用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);
于 2017-11-16T15:01:52.113 回答
-3

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

例如,

gradlew clean build test
于 2017-08-14T19:16:36.933 回答