gpt4 book ai didi

java - 与第三方类(class)时的模仿

转载 作者:行者123 更新时间:2023-11-29 04:29:34 25 4
gpt4 key购买 nike

我需要在 Mockito.when 中使用第三方类作为参数。该类没有 equals 实现,因此 Mockito.when 总是返回 null,除非使用 any()

下面总是返回空值:

when(obj.process(new ThirdParytClass())).thenReturn(someObj);

然而,这是可行的

when(obj.process(any(ThirdParytClass.class))).thenReturn(someObj);

但是,问题是 process() 方法在实际代码中被调用了两次,而 any() 的使用是模棱两可的,无助于覆盖多个场景进行测试。

延长类(class)没有帮助,还会导致其他并发症。

有没有办法解决这个问题。

最佳答案

如果一个类没有实现(合理的)equals(Object),您始终可以通过实现自己的 ArgumentMatcher 自己匹配实例. Java 8 的函数式接口(interface)使得这很容易编写(虽然在早期版本中这不是一个很大的困难,但仍然如此):

when(obj.process(argThat(tpc -> someLogic()))).thenReturn(someObj);

然而,通常情况下,如果您只想比较类的数据成员,内置的 refEq匹配器可以解决问题:

ThirdParytClass expected = new ThirdParytClass();
// set the expected properties of expected

when(obj.process(refEq(expected))).thenReturn(someObj);

关于java - 与第三方类(class)时的模仿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44337836/

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