【问题标题】:Method with Optional return type returns null value具有可选返回类型的方法返回空值
【发布时间】: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,因为 somethingnull。不应该是 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


【解决方案1】:

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

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

当你不这样做时,Mock 的方法默认返回null(不是Optional.empty()!)

【讨论】:

  • 我为什么要模拟我正在测试的方法@Nikolai Shevchenko。我应该只模拟要测试的方法中的依赖代码。
  • @VipulLohani 只是一个假设 :) 这是非常常见的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-14
  • 1970-01-01
  • 2019-07-02
  • 2014-08-24
  • 2016-04-20
相关资源
最近更新 更多