Question

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

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);
}

But I am getting exception as -

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

Is there anything wrong I am doing here?

Was it helpful?

Solution

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 });

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top