我有下面定义的两种方法。
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()
为something
,因此我得到了null
的NullPointerException。它不是Optional.empty()吗?无法获取为什么null
返回getSomething()
值的原因。
由于您从单元测试中调用了getSomething
,所以我猜想client
是一个模拟,您忘了显式地模拟它的方法,如下所示:
// with Mockito
when(client.getSomething(any(String.class)))
.thenReturn(Optional.of("someResponse"));
[如果不这样做,那么Mock的方法默认返回null