【发布时间】:2020-09-23 13:31:34
【问题描述】:
我有下面定义的两种方法。
public Optional<String> getSomething(final String input) throws ContainerException {
try{
return Optional.of(globals.getParam(GlobalsClass.Keys.SOME_ID).strict().stringValue());
} catch(ContainerException e) {
log.error(e);
throw e;
}
}
@Test
public void test_get_something() {
try {
final Optional<String> something = client.getSomething("24430881");
if(something.isPresent()) {
System.out.println(something.get());
}
} catch (ContainerException e) {
Assert.fail("Should not have thrown any exception");
}
}
问题是我得到了 something.isPresent() 的 NullPointerException,因为 something 是 null。不应该是 Optional.empty() 吗?不明白为什么getSomething() 会返回null 值。
【问题讨论】:
-
阅读 api 文档? docs.oracle.com/javase/8/docs/api/java/util/Optional.html#of-T- 如果传入的值为 null,则会引发 NPE。使用 ofNullable 代替。
-
还是同样的错误@NathanHughes
-
您发布的代码既不能返回
null,也不能返回空选项。因此,您发布的代码与产生该异常的代码不匹配。顺便说一句,对于单元测试,不需要使用Assert.fail(…)处理程序来捕获异常。只需在方法中添加throws声明,然后让异常转到调用者。如果发生异常,测试将被标记为失败。
标签: java nullpointerexception optional