找不到兼容的方法:将对象传递给方法时出错? [英] No compatible method found: error while passing object to a method?

查看:215
本文介绍了找不到兼容的方法:将对象传递给方法时出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为一些旧的遗留代码编写junit

I am trying to write junit for some old legacy code we have

下面是DataLogger类中我正在编写junit的方法,我正在使用jmockit -

Below is the method in DataLogger class for which I am writing junit and I am using jmockit -

private Object[] extractMessageObjects(final Object... objects) {
    Object[] result = new Object[objects.length - 1];

    System.arraycopy(objects, 0, result, 0, result.length);

    return result;
}

因此,以下测试应该可以正常工作。对吗?

So below test should work fine. Right?

@Test
public void testLogDebugWithStackTrace() {
    DataLogger logger = DataLogger.getInstance(ClientTest.class);

    Object obj[] = new Object[] {1};
    Deencapsulation.invoke(logger, "extractMessageObjects", obj);
}

但我得到例外 -

No compatible method found: extractMessageObjects(java.lang.Integer)

我在这里做错了吗?

推荐答案

中调用(..)您使用的方法,方法的参数类型是从 Object [] 中的元素类型解析的。由于您的整数,jmockit将尝试查找接受的方法和 Integer 。它会失败,因为这样的方法不存在。

In the invoke(..) method you use, the type of the parameters for the method are resolved from the type of elements in your Object[]. Since yours contains an Integer, jmockit will try to find a method that accepts and Integer. It will fail since such a method doesn't exist.

No compatible method found: extractMessageObjects(java.lang.Integer)

相反,您可以使用接受参数类型的重载方法

Instead, you can use the overloaded method that accepts the parameter types

Deencapsulation.invoke(new Example(), "extractMessageObjects",
            new Class<?>[] { Object[].class }, (Object) new Object[] { 1 });

这样它就可以正确地找到合适的方法而不需要使用你所使用的参数类型的提示。请注意,您必须转换最后一个参数,以便将其用作 Deencapsulation.invoke的目标 Object [] 参数中的唯一元素( ..)方法。

So that it can find the appropriate method correctly without hints from the type of arguments you use. Note that you have to cast the last argument so that it is used as the only element in the target Object[] parameter of the Deencapsulation.invoke(..) method.

这篇关于找不到兼容的方法:将对象传递给方法时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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