"resource.adaptTo" NullPointer 单元测试 AEM Sling 模型 Java

"resource.adaptTo" NullPointer Unit test AEM Sling Model Java

我正在 AEM 中对 Sling 模型 进行非常基本的单元测试,所以,当我 运行测试我得到以下错误:

[ERROR] CtaModelTest.testGetText:36 NullPointer

这是我的 Java 代码,该模型是一个非常基本的 Sling AEM 模型,我使用 @ModelAnnotation 如下:

@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
package com.myproject.core.models;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import com.day.cq.wcm.api.Page;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import junitx.util.PrivateAccessor;
import javax.inject.Inject;

@ExtendWith(AemContextExtension.class)
class CtaModelTest {
    private static final String COMPONENT_PATH = "/content/campaigns/myproject/master/demo-campaign/demo-email";
    
    private CtaModel ctaModel;

    private Page page;
    private Resource resource;

    @BeforeEach
    public void setup(AemContext context) throws Exception {
        
        context.load().json("/ctaModelTest.json", COMPONENT_PATH);
        context.addModelsForClasses(CtaModel.class);
        
        resource = context.resourceResolver().getResource(COMPONENT_PATH + "/jcr:content/par/hero/cta");
        ctaModel = resource.adaptTo(CtaModel.class);
    }

    @Test
    void testGetText() throws Exception {
        String txt = ctaModel.getText();
        assertNotNull(txt);
    }
}

谁能帮我解决一下?

似乎resource.adaptTo(CtaModel.class)返回了null。问题是,如果有任何失败, adaptTo(...) returns null 非常安静。因此,SlingMocks 文档建议 ModelFactory.createModel(...) 而不是 SlingModels adaptTo(...)

https://sling.apache.org/documentation/development/sling-mock.html#model-instantiation

// load some content into the mocked repo
context.load().json(..., "/resource1");

// load resource
Resource myResource = content.resourceResolver().getResource("/resource1");

// instantiate Sling Model (adaptable via Resource)
// this will throw exceptions if model cannot be instantiated
MyModel myModel = context.getService(ModelFactory.class).createModel(myResource, MyModel.class);

如果您这样做,ModelFactory 将记录错误详细信息,以及无法创建 Sling 模型的原因。所以你知道,问题是什么,你不需要猜测。

如果 init 方法存在问题,特别是如果注入的任何对象(如 currentPage 或服务)为 null,则即使使用 createModel,模型也会 return 静默为 null。

https://myaemlearnings.blogspot.com/2020/08/unit-testing-in-aem-debugging-issues-in.html