首页 > 解决方案 > 如何获取 Eclipse 空分析以使用 JUnit 中的 assertNotNull

问题描述

如何让 eclipses null 分析与 jUnit 5 中的 assertNotNull 一起使用。在下面的程序中,我收到“Potientiel null 警告”,尽管由于上面的 assertNotNull 行,leaf 不可能为 null。

如果我将 assertNotNull 更改为 assert(leaf!=null) 警告就会消失。

根据这个(旧)链接,eclipse应该支持使用junit断言,并且我启用了“启用基于注释的空分析”

https://bugs.eclipse.org/bugs/show_bug.cgi?id=382069

LeafNode leaf=getLeafMayBeNull();   assertNotNull(leaf);
assertEquals(Long.valueOf(42),leaf.getLong());

标签: javaeclipse

解决方案


事实上,对于 JUnit 4,afterassertNotNull(o) o不能null硬编码的事实(在提到的 bug中跟踪并通过这个 commit 实现)。但是对于 JUnit 5,这还没有完成(参见org.eclipse.jdt.internal.compiler.lookup.TypeConstants常量 fororg.junit.Assert但没有常量 for org.junit.jupiter.api.Assertions)。请将此报告给 Eclipse。

作为解决方法,您可以使用以下实用程序方法来避免潜在的空指针访问问题

static <T> T notNull(@Nullable T o) {
    assertNotNull(o);
    if (o == null) throw new RuntimeException();
    return o;
}

使用此实用程序方法,给定的代码片段如下所示:

LeafNode leaf = notNull(getLeafMayBeNull());
assertEquals(Long.valueOf(42),leaf.getLong());

推荐阅读