user3573403
user3573403

Reputation: 1812

Why unit test fail with Optional return type?

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<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());
    }

}

Upvotes: 0

Views: 743

Answers (1)

Progman
Progman

Reputation: 19555

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.

Upvotes: 4

Related Questions