如何在 Mockito 中匹配可能的空参数 [英] How to match a possible null parameter in Mockito

查看:71
本文介绍了如何在 Mockito 中匹配可能的空参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证我正在测试的类是否调用了正确的依赖类的方法.所以我试图匹配方法参数,但我并不真正关心这个测试中的实际值,因为我不想让我的测试变得脆弱.

I'm trying to verify that the class I'm testing calls the correct dependency class's method. So I'm trying to match the method parameters, but I don't really care about the actual values in this test, because I don't want to make my test brittle.

但是,我在设置它时遇到了麻烦,因为 Mockito 认为我期望的行为是一个错误:https://github.com/mockito/mockito/issues/134

However, I'm running into trouble setting it up because Mockito has decided that the behaviour I'm expecting is a bug: https://github.com/mockito/mockito/issues/134

那么为可能为 null 的参数定义 ArgumentMatcher 的正确方法是什么?

So what't the correct way to define an ArgumentMatcher for a parameter that might be null?

问题 #134已修复",此代码失败,因为匹配器仅在第一种情况下匹配.如何定义匹配器以在所有 4 种情况下工作?

With issue #134 "fixed", this code fails because the matchers only match in the first case. How can I define a matcher to work in all 4 cases?

MyClass c = mock(MyClass.class);

c.foo("hello", "world");
c.foo("hello", null);
c.foo(null, "world");
c.foo(null, null);

verify(c, times(4)).foo(anyString(), anyString());

推荐答案

来自 any()

自 Mockito 2.1.0 起,只允许非空 String.作为这个是一个可为空的引用,建议的 API 以匹配null 包装器将是 isNull().我们感受到了这一点与 Mockito 相比,更改将使测试工具更安全1.x.

Since Mockito 2.1.0, only allow non-null String. As this is a nullable reference, the suggested API to match null wrapper would be isNull(). We felt this change would make tests harness much safer that it was with Mockito 1.x.

因此,匹配可为空字符串参数的方法是显式声明:

So, the way to match nullable string arguments is explicit declaration:

nullable(String.class)

这篇关于如何在 Mockito 中匹配可能的空参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆