首页 > 解决方案 > aem 的单元测试不涵盖条件

问题描述

我是单元测试的新手。我正在将 junit5 用于 aem 6.5 应用程序。我正在尝试编写单元测试,以便我可以迁移到需要至少 50% 单元测试的云,这就是我现在在做什么。我的代码有一个 getTags() 的 init 方法。我的单元测试工作正常,但 jacoco 报告了一条未被覆盖的行。任何帮助将不胜感激,让我朝着正确的方向前进。

我有这堂课:

@Self
private SlingHttpServletRequest request;

@ValueMapValue
private List<String> tags;

@Override
public String getExportedType() {
    return RESOURCE_TYPE;
}

@PostConstruct
public void init() {
    Resource tagsNode = request.getResource().getChild("tags");
    tags = new ArrayList<>();
    if (tagsNode!=null) {
        for (Resource child : tagsNode.getChildren()) {
            TagModel tag = child.adaptTo(TagModel.class);
            tags.add(tag.getTag());
        }
    }
}

public List<String> getTags() {
    return this.tags;
}

我有这个针对 aem 的单元测试

@Test
void testGetTags() {
    List<String> expected = new ImmutableList.Builder<String>()
            .add("4")
            .add("22")
            .build();

    ctx.currentResource("/content/blog_placeholder");

    BlogPlaceholderModel blogPlaceholderModel = ctx.request().adaptTo(BlogPlaceholderModel.class);

    List<String> actual = blogPlaceholderModel.getTags();

    assertEquals(expected, actual);
}

@Test
void testGetExportedType() {
    final String expected = "furniture-row/components/content/blog-placeholder";

    ctx.currentResource("/content/blog_placeholder");

    BlogPlaceholderModel blogPlaceholderModel = ctx.request().adaptTo(BlogPlaceholderModel.class);

    String actual = blogPlaceholderModel.getExportedType();

    assertEquals(expected, actual);
}

出于某种原因,我的测试没有涵盖 if 条件:

在此处输入图像描述

我错过了什么?谢谢

标签: unit-testingjunitaemjunit5

解决方案


您的测试部分覆盖了这条线。

您确实对这种情况进行了测试,(tagsNode != null) == true但对(tagsNode != null) == false. 因此,该行是黄色的,表示并未if涵盖该语句的所有“分支”。


推荐阅读