gpt4 book ai didi

mockito - 如何在 Mockito 中匹配可能的空参数

转载 作者:行者123 更新时间:2023-12-03 12:03:47 31 4
gpt4 key购买 nike

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

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

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

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

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() 的 javadocs

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.



因此,匹配可为空字符串参数的方法是显式声明:
nullable(String.class)

关于mockito - 如何在 Mockito 中匹配可能的空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40225011/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com