繁体   English   中英

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

[英]"resource.adaptTo" NullPointer Unit test AEM Sling Model Java

我正在对AEM 中的Sling 模型进行非常基本的单元测试,因此,当我运行测试时,出现以下错误:

[错误] 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。 问题是,如果出现任何失败,该adapterTo(...) 会非常安静地返回null。 因此,SlingMocks 文档建议为 SlingModels 使用ModelFactory.createModel(...)而不是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,model 也会静默返回 null。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM