我有一个Sling模型类,其中包含对我的服务的引用:
@OSGiService
PlanService planService;
此服务引用ResourceResolverFactory,以获取具有“admin user”的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);
答案 0 :(得分:2)
试试这个:
osgiContext.registerService(ResourceResolverFactory.class, new MockResourceResolverFactory());
OsgiContext
的Javadoc是here
答案 1 :(得分: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);
答案 2 :(得分:-2)
在测试之前尝试清理和构建项目。
例如,
gradlew clean build test