具有可选返回类型的方法返回空值

问题描述 投票:-1回答:1

我有下面定义的两种方法。

    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()值的原因。

java nullpointerexception optional
1个回答
0
投票

由于您从单元测试中调用了getSomething,所以我猜想client是一个模拟,您忘了显式地模拟它的方法,如下所示:

// with Mockito
when(client.getSomething(any(String.class)))
    .thenReturn(Optional.of("someResponse"));

[如果不这样做,那么Mock的方法默认返回null

© www.soinside.com 2019 - 2024. All rights reserved.