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

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

上一篇:Mockito - 拦截模拟上的任何方法调用 下一篇:你如何模拟 JavaFX 工具包初始化?

相关文章