AEM 6.3,wcm.io:在@Act ivate方法中吊索MockResource null

问题描述 投票:0回答:2

我有一个具有@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);
mocking osgi adobe aem sling
2个回答
0
投票

您必须调用buildTitleListActivate(新的Java编码约定?),因为“OSGI声明性服务注释”在单元测试中没有用。您根本没有容器来调用方法。


0
投票

感谢@Jens,我发现ResourceResolver现在实现了AutoClosable接口(从6.2开始,我们使用的是6.3.1.2)所以我可以删除我们的自定义工厂并使用默认的ResourceResolverFactory,现在一切正常。

© www.soinside.com 2019 - 2024. All rights reserved.