在同一个模拟上使用多个 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)