在同一个模拟上使用多个 ArgumentMatchers

Using Multiple ArgumentMatchers on the same mock(在同一个模拟上使用多个 ArgumentMatchers)
本文介绍了在同一个模拟上使用多个 ArgumentMatchers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试在 Mock 上使用 Mockito 来做到这一点:
当 Mock.someMethod(..) 用 argument1 调用时 --> return result1
当 Mock.someMethod(..) 用 argument2 调用时 --> return result2
当 Mock.someMethod(..) 用 argument3 调用时 --> return result3

I am trying to do this using Mockito on a Mock:
When Mock.someMethod(..) is called with argument1 --> return result1
When Mock.someMethod(..) is called with argument2 --> return result2
When Mock.someMethod(..) is called with argument3 --> return result3

    when(mock.method(Matchers.argThat(new MyMatcher1() {

        @Override
        public boolean matches(Object arg0) {
                   // comparision logic
        }
    }))).thenReturn(result1);

    when(mock.method(Matchers.argThat(new MyMatcher2() {

        @Override
        public boolean matches(Object arg0) {
                   // comparision logic
        }
    }))).thenReturn(result2);

    when(mock.method(Matchers.argThat(new MyMatcher3() {

        @Override
        public boolean matches(Object arg0) {
                   // comparision logic
        }
    }))).thenReturn(result3);

但是 Mockito 正确地存根第一个,但是在第二个上它会抛出 NullPointer 异常,因为它出于某种原因尝试使用 null agrument 运行 Matcher.我不确定它是否受支持.

But Mockito stubs the first one correctly, but on the second one it throws NullPointer exception as it for some reason tries to run the Matcher with null agrument. I am not sure if it is supported.

如果这不是正确的方法,如何使用 Mockito 来实现?谢谢.

If this is not the correct way, how to achieve this with Mockito? Thanks.

推荐答案

我现在能够通过在自定义 ArgumentMatcher 中进行空检查来解决这个问题.它起作用了,因为 NPE 仅在 Mockito 调用 when() 语句时才在启动期间.此时它甚至不应该调用 ArgumentMatcher.matches() !感觉就像 Mockito 中的一个错误.

I was able to get around the problem for now, by having a null check in the custom ArgumentMatcher. It worked, as the NPE is only during startup when Mockito is calling when() statements. It shouldn't even call ArgumentMatcher.matches() at this time! It feels like a bug in Mockito.

这篇关于在同一个模拟上使用多个 ArgumentMatchers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)