我正在 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(...) 会非常安静地返回 null。因此,SlingMocks 文档建议为 SlingModel 使用 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 模型的原因。所以您知道问题出在哪里,无需猜测。
关于java - "resource.adaptTo"NullPointer 单元测试 AEM Sling 模型 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64867814/