Mockito:使用类型兼容的参数验证重载的方法 [英] Mockito: Verifying overloaded methods with type-compatible arguments

查看:136
本文介绍了Mockito:使用类型兼容的参数验证重载的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑您要使用包含以下方法签名的Mockito 模拟接口:

Consider you want to mock an interface using Mockito containing the following method signatures:

public void doThis(Object o);

public void doThis(Object... o)

我需要验证doThis(Object o)(而不是其他方法)已被完全调用一次.

I need to verify that doThis(Object o) (and not the other method) has been invoked exactly one time.

首先,我认为以下代码可以解决问题:

First I thought that the following line would do the trick:

verify(mock, times(1)).doThis(anyObject());

但是,由于这似乎在Windows上可行,但在Linux上却不可行,因为在这种环境下,期望调用其他doThis方法.
这是因为 anyObject()参数似乎同时匹配两个方法签名,并且以一种或多或少不可预测的方式选择了一个.

However, as this seems to work on Windows, it doesn't on Linux because in this environment, a call to of the other doThis method is expected.
This is caused because the anyObject() argument seems to match both method signatures and one is chosen in a more or less unpredictable way.

如何强制 Mockito始终选择doThis(Object o) 进行验证?

How can I enforce that Mockito always chooses doThis(Object o) for verification?

推荐答案

这不是模拟问题.

This is not a mockito issue.

在进一步调查期间,

During further investigating, I realized that the actual method is chosen at compile-time (JLS §15.12.2). So basically the class files differed between windows and linux which caused different mockito behavior.

不建议使用该接口(请参见Effective Java, 2nd Edition, Item 42). 我将其更改为与以下内容匹配:

The interface is discouraged (see Effective Java, 2nd Edition, Item 42). I changed it to match the following:

public void doThis(Object o);

public void doThis(Object firstObj, Object... others)

进行此更改后,将始终选择预期的(第一种)方法.

With this change the expected (first) method will always be chosen.

还剩下一件事:
为什么Windows上的Java编译器(Eclipse编译器)会产生与Linux上的Oracle JDK Javac不同的输出?

One thing is still left:
Why does the java compiler on windows (eclipse compiler) produce a different output than Oracle JDK javac on Linux?

这可能是ECJ中的错误 ,因为我希望这里的Java语言规范非常严格.

This might be a bug in ECJ because I would expect that the java language spec is pretty strict here.

这篇关于Mockito:使用类型兼容的参数验证重载的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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