在同一个模拟上使用多个ArgumentMatchers [英] Using Multiple ArgumentMatchers on the same mock

查看:90
本文介绍了在同一个模拟上使用多个ArgumentMatchers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在模拟中使用Mockito执行此操作:

当使用argument1调用Mock.someMethod(..)时 - >返回result1

当Mock使用argument2调用.someMethod(..) - >返回result2

当使用argument3调用Mock.someMethod(..)时 - >返回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异常reason尝试使用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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆