我有一个具有@Activate方法的OSGI服务。在activate方法中,我调用了一个名为' buildTitleList'我查询一些资源(页面)并在列表中收集他们的标题。此代码在运行环境中工作,但不在我的单元测试中。
我按照以下方式在我的上下文中创建页面:
aemContext.create().page("/content/test-page', "/apps/platform-company/templates/home-page", "test-tile");
如果我调试单元测试,我可以看到我在' buildTitleList'中查询的资源。是空的(注意:我确信我的路径是正确的)
当我打电话给' buildTitleList'直接在我的单元测试它工作。这是正常的行为,有没有办法确保@Activate方法也可以在上下文中看到新创建的页面?
测试:
@Test
public void checkTitles() {
TitleService titleService = context.getService(TitleService.class);
System.out.println(); //If I set a breakpoint here and look into the TitleService instance the list of titles is still 0
}
TitleService:
public class TitleService {
private List<String> titles;
public TitleService() {
this.titles = new CopyOnWriteArrayList<>();
}
...
public void buildTitleList() throws RepositoryException, LoginException, WCMException {
// Gather title code here (incl. newlist). This works on a running instance but the resoure is always null when calle from within an @Activa method
this.titles.addAll(newlist);
}
...
@Activate
protected void Activate() {
buildTitleList();
}
}
设置代码:
...
public static AemContext getAemContext(RunMode runMode) {
if (aemContext != null) {
aemContext.runMode(runMode.getValue());
return aemContext;
} else {
aemContext = newAemContext();
aemContext.runMode(runMode.getValue());
return aemContext;
}
}
public static AemContext newAemContext() {
return new AemContextBuilder()
.resourceResolverType(ResourceResolverType.JCR_MOCK)
.afterSetUp(SETUP_CALLBACK)
.build();
}
private static final AemContextCallback SETUP_CALLBACK = aemContext -> {
// context path strategy
MockCAConfig.contextPathStrategyRootTemplate(aemContext, Template.HOME_PAGE.getValue());
// register sling models
...
aemContext.registerInjectActivateService(new AutoClosableResourceResolverFactory());
aemContext.registerInjectActivateService(new TitleService());
createBlueprintPages(aemContext);
TestInformation testInformation = TestInformation.getInstance();
for (TestLiveCopyInformation info : testInformation.getLiveCopyInformationList()) {
aemContext.load().json(info.getResourcePath(), info.getContentRoot() + "/" + info.getLanguage().getIsoCode());
}
// set default current page
aemContext.currentPage(CONTENT_ROOT);
};
...
测试中的规则:
@Rule
public final AemContext context = AppAemContext.getAemContext(RunMode.AUTHOR);
答案 0 :(得分:0)
您必须调用buildTitleList
或Activate
(新的Java编码约定?),因为&#34; OSGI声明性服务注释&#34;在单元测试中没用。你根本没有容器来调用这些方法。
答案 1 :(得分:0)
感谢@Jens我发现ResourceResolver现在实现了AutoClosable接口(从6.2开始,我们使用的是6.3.1.2)所以我可以删除我们的自定义工厂并使用默认的ResourceResolverFactory,现在一切正常。