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.

3

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".

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest