Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Mockito.anyLong() do?

I have to test a method which takes a Long as argument. I have to test it for any value of the Long and also in case it's null. Does Mockito.anyLong() automatically test both cases? null and any value of the Long? Or randomly picks up a value between any long value and null? Considering that these are the docs about anyLong():

anyLong

public static long anyLong()

any long, Long or null.

See examples in javadoc for Matchers class

Returns:
    0.

Thanks in advance.

like image 700
Rollerball Avatar asked Jan 03 '14 08:01

Rollerball


2 Answers

It's a matcher, not a test value generator. It's used for saying things like "I expect this stubbed method to be called with any long, Long or null but I don't care about the exact value".

like image 128
mpartel Avatar answered Sep 27 '22 21:09

mpartel


If you have long parameter and you manage to pass null as an argument to mock there will be NPE. If you have Long parameter anyLong() will allow Long and null, long will be autoboxed to Long by compiler. Try this

public class X  {
    long x(Long arg) {
        return 0;
    }

    public static void main(String[] args) {
        X x = mock(X.class);
        when(x.x(anyLong())).thenReturn(0L);
        System.out.println(x.x(null));
    }
}

it will print

0
0
like image 44
Evgeniy Dorofeev Avatar answered Sep 27 '22 20:09

Evgeniy Dorofeev