“resource.adapto”nullpointer单元测试aem sling model java

3npbholx  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(261)

我正在为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);
    }
}

有人能帮我修一下吗?

mzmfm0qo

mzmfm0qo1#

看来 resource.adaptTo(CtaModel.class) 返回null。问题是,如果任何操作失败,adapto(…)都会非常安静地返回null。因此,slingmocks文档建议 ModelFactory.createModel(...) 而不是 adaptTo(...) 对于slingmodels。
https://sling.apache.org/documentation/development/sling-mock.html#model-示例化

// 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模型。所以你知道,问题是什么,你不需要猜。

相关问题