Java Mockito.anyLong() 有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20899579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:07:15  来源:igfitidea点击:

What does Mockito.anyLong() do?

javajunitmockito

提问by Rollerball

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():

我必须测试一个以 Long 作为参数的方法。我必须测试它的任何 Long 值,以及它是否为空。Mockito.anyLong() 是否会自动测试这两种情况?null 和 Long 的任何值?或者在任意长值和空值之间随机选取一个值?考虑到这些是关于 anyLong() 的文档:

anyLong

public static long anyLong()

any long, Long or null.

See examples in javadoc for Matchers class

Returns:
    0.

任何龙

public static long anyLong()

any long, Long or null.

See examples in javadoc for Matchers class

Returns:
    0.

Thanks in advance.

提前致谢。

采纳答案by mpartel

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

它是一个匹配器,而不是一个测试值生成器。它用于表示诸如“我希望使用任何 long、Long 或 null 调用此存根方法,但我不关心确切值”之类的内容。

回答by Evgeniy Dorofeev

If you have longparameter and you manage to pass nullas an argument to mock there will be NPE. If you have Longparameter anyLong()will allow Longand null, longwill be autoboxed to Longby compiler. Try this

如果您有long参数并且您设法将其null作为参数传递给模拟,则会有 NPE。如果您有Long参数anyLong()将允许Longnulllong将被Long编译器自动装箱。尝试这个

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