我有下面定义的两种方法。
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
值。
最佳答案
由于您从单元测试中调用 getSomething
,我猜测 client
是一个 Mock,并且您忘记显式模拟它的方法,如下所示:
// with Mockito
when(client.getSomething(any(String.class)))
.thenReturn(Optional.of("someResponse"));
当你不这样做时,Mock 的方法默认返回 null
(不是 Optional.empty()
!)
关于java - 具有可选返回类型的方法返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62196762/