为什么带有Optional返回类型的单元测试会失败?

huangapple go评论58阅读模式
英文:

Why unit test fail with Optional return type?

问题

考虑以下使用Mockito(版本2.23.4)进行单元测试的代码。我不知道为什么测试会失败。如果我将 a.get(null) 更改为 a.get(2L) 或任何 Long 值,测试就会通过。那么为什么 null 在应该适用于 anyLong() 的情况下失败了呢?

public class A {

    public Optional<Long> get(Long l) {
        return Optional.empty();
    }

    @Test
    public void test() {
        A a = Mockito.mock(A.class);
        Mockito.when(a.get(anyLong())).thenReturn(Optional.of(1L));
        Assert.assertTrue(a.get(null).isPresent());
    }

}
英文:

Consider the following codes using Mockito (version 2.23.4) for unit testing. I have no idea why the test fail. If I change a.get(null) to a.get(2L) or any Long value, the test will pass. So why is null failing when anyLong() should work for null values?

public class A {

    public Optional&lt;Long&gt; get(Long l) {
        return Optional.empty();
    }

    @Test
    public void test() {
        A a = Mockito.mock(A.class);
        Mockito.when(a.get(anyLong())).thenReturn(Optional.of(1L));
        Assert.assertTrue(a.get(null).isPresent());
    }

}

答案1

得分: 4

anyLong()匹配器不再包括NULL。请查看ArgumentMatchers.anyLong()的文档:

> 任何long或非nullLong
>
> 自从Mockito 2.1.0版本以后,只允许有值的Long,因此null不再是一个有效的值。

这与Mockito 1.9.5不同:

> 任何longLongnull

英文:

The anyLong() matcher does not include NULL (anymore). See the documentation of ArgumentMatchers.anyLong():

> Any long or non-null Long.
>
> Since Mockito 2.1.0, only allow valued Long, thus null is not anymore a valid value.

This is different from Mockito 1.9.5:

> Any long, Long or null.

huangapple
  • 本文由 发表于 2020年10月22日 16:42:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64478485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定