You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AEM 6.5中HelloWorldModel单元测试类运行抛出空指针异常

AEM 6.5 Sling Model单元测试空指针异常解决方案

问题场景

在AEM 6.5环境中基于JUnit 5与AemContext编写HelloWorldModel基础单元测试:在@BeforeEach修饰的setup方法中创建测试页面、绑定sling:resourceType的测试资源,将资源适配为HelloWorldModel实例,在testGetMessage测试方法中调用模型的getMessage方法做断言校验时,抛出java.lang.NullPointerException,错误定位在testGetMessage方法内。
原始测试代码如下:

class HelloWorldModelTest {

    private HelloWorldModel hello;

    private Page page;
    private Resource resource;

    @BeforeEach
    public void setup(AemContext context) throws Exception {

        // prepare a page with a test resource
        page = context.create().page("/content/mypage");
        resource = context.create().resource(page, "hello",
            "sling:resourceType", "aemgeeks/components/helloworld");

        // create sling model
        hello = resource.adaptTo(HelloWorldModel.class);
    }

    @Test
    void testGetMessage() throws Exception {
        // some very basic junit tests
        String msg = hello.getMessage();
        assertNotNull(msg);
        assertTrue(StringUtils.contains(msg, resource.getResourceType()));
        assertTrue(StringUtils.contains(msg, page.getPath()));
    }

}

异常根因

空指针的直接触发原因是resource.adaptTo(HelloWorldModel.class)执行后返回了null,后续测试方法直接调用hello.getMessage()时访问了空对象。
适配返回null的常见原因有3个:

  • 测试使用的AemContext默认不会自动扫描项目中的Sling Model类,未手动注册模型的情况下,上下文找不到对应适配规则,直接返回null
  • HelloWorldModel类本身的Sling Model注解配置错误:要么未标注@Model注解,要么注解中adaptables属性未指定Resource.class,无法从资源对象完成适配
  • 测试资源绑定的sling:resourceType值,和HelloWorldModel类@Model注解中声明的resourceType不匹配,适配校验不通过返回null

修复方案

  1. 在setup方法的资源创建逻辑前,添加Sling Model注册代码,让AemContext识别待测试的模型类,同时增加适配结果非空校验,提前暴露适配失败问题:
@BeforeEach
public void setup(AemContext context) throws Exception {
    // 注册待测试的Sling Model
    context.addModelsForClasses(HelloWorldModel.class);
    // 如需扫描整个模型包,可替换为:
    // context.addModelsForPackage("com.adobe.aem.guides.wknd.core.models");

    // 创建测试页面与资源
    page = context.create().page("/content/mypage");
    resource = context.create().resource(page, "hello",
        "sling:resourceType", "aemgeeks/components/helloworld");

    // 适配模型并做非空校验
    hello = resource.adaptTo(HelloWorldModel.class);
    assertNotNull(hello, "HelloWorldModel适配失败,请检查模型注解与资源类型配置");
}
  1. 核对HelloWorldModel类的注解配置,确保和测试配置完全对齐:
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;

@Model(
    adaptables = Resource.class,
    resourceType = "aemgeeks/components/helloworld" // 与测试中设置的sling:resourceType值完全一致
)
public class HelloWorldModel {
    // 内部属性注入、业务方法实现
    public String getMessage() {
        // 原有业务逻辑
    }
}
  1. 完成上述配置后重新执行单元测试即可正常运行。

内容的提问来源于stack exchange,提问作者sowjanya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 12:00:50