gpt4 book ai didi

java - 如何让 eclipses null 分析使用 JUnit 中的assertNotNull

转载 作者:行者123 更新时间:2023-12-02 06:00:04 25 4
gpt4 key购买 nike

如何让 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());

最佳答案

事实上,对于 JUnit 4 事实上,在 assertNotNull(o) 之后o不能是null硬编码(在 mentioned bugimplemented via this commit 中跟踪)。但是对于 JUnit 5,这还没有完成(参见 org.eclipse.jdt.internal.compiler.lookup.TypeConstants org.junit.Assert 的常量,但没有 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());

关于java - 如何让 eclipses null 分析使用 JUnit 中的assertNotNull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55983588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com