Java 用于 int 原始类型的 Mockito

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21980728/
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 11:48:41  来源:igfitidea点击:

Mockito for int primitive

javamockito

提问by user3278325

If I am using a Wrapper class type variable as argument Mockito test case is getting pass but, how to write Mockito test case for int primitive type variable which is an argument to a method in ServiceImpl.

如果我使用 Wrapper 类类型变量作为参数,Mockito 测试用例正在通过,但是,如何为作为 ServiceImpl 中方法的参数的 int 原始类型变量编写 Mockito 测试用例。

回答by Jeff Bowman

You may have some trouble with anyor argThatfor primitive-type arguments to whenand verify. Those Object-centric methods do their work with side-effects correctly, but they tend to return nullfor a dummy return value, which doesn't work for Java unwrapping primitives via auto-boxing.

您可能有一些麻烦any或者argThat对原始类型参数whenverify。那些以对象为中心的方法可以正确地处理副作用,但它们往往会返回null一个虚拟返回值,这对于通过自动装箱的 Java 解包原语不起作用。

Luckily, the org.mockito.ArgumentMatchersclass has a full complement of primitive-centric methods (of which I've listed the intmethods here):

幸运的是,org.mockito.ArgumentMatchers该类具有完整的以原始为中心的方法(我在int此处列出了其中的方法):

static int anyInt()
static int eq(int value)
static int intThat(org.hamcrest.ArgumentMatcher<java.lang.Integer> matcher)

See all of them at the documentation for the ArgumentMatchers class.

在 ArgumentMatchers 类文档中查看所有这些。

回答by Ketan

I know that the question has been more than 4 years and 8 months old but for the sake of clear solution as of today, I am posting this

我知道这个问题已经超过 4 年零 8 个月了,但为了今天的明确解决方案,我发布了这个

In my case, the method signature to be tested is

就我而言,要测试的方法签名是

public SomeObject create(String code, int status)

so the test code for verifying the argument values when the method was invoked would be following

所以在调用方法时验证参数值的测试代码将如下

verify(this.service).create(
        argThat(code -> "dummy_code".equals(code)),
        intThat(status -> status == 105));

If I go with the argThateven for int (or any primitive types) then mockito throws NPE

如果我使用argThat即使对于 int(或任何原始类型),那么 mockito 会抛出NPE

Currently I am using org.mockito:mockito-core:jar:2.15.0which must have been advanced considering the time when the question was asked! But thinking that this might be helpful to people... Thanks,

目前我正在使用org.mockito:mockito-core:jar:2.15.0考虑到提出问题的时间,它一定是先进的!但认为这可能对人们有帮助......谢谢,