Question

Below is my private method in my DataTap class and I am trying to junit test this private method using jmockit -

private void parseResponse(String response) throws Exception {
    if (response != null) {
        // some code
    }
}

So below is the junit test I wrote but for null case, it is throwing NPE somehow on the junit test itself.

DataTap tap = new DataTap();
Deencapsulation.invoke(tap, "parseResponse", "hello");

// this line throws NPE
Deencapsulation.invoke(tap, "parseResponse", null);

So my question is - Is there any way I can pass null string to parseResponse method using JMOCKIT as part of junit testing?

This is what I am seeing on that line -

The argument of type null should explicitly be cast to Object[] for the invocation of the varargs method invoke(Object, String, Object...) from type Deencapsulation. It could alternatively be cast to Object for a varargs invocation

Was it helpful?

Solution

A quick glance at the documentation suggests that what you're trying to do with that signature is not possible:

...if a null value needs to be passed, the Class object for the parameter type must be passed instead

If that's the case, then pass in the Class object as well as the instance.

Deencapsulation.invoke(tap, "parseResponse", String.class);

OTHER TIPS

Do what the error says. That is, change the line to this:

Deencapsulation.invoke(tap, "parseResponse", (Object) null);

I did like that when I need to pass null String in toString method i.e via casting the null into required type

mockedObject.toString((String) null)

You are using the convenience method and you need to use the full method. There are two methods to invoke a method on an object instance. The first method works by getting the parameterTypes from the nonNullArgs.

Deencapsulation.invoke(instance, methodName, nonNullArgs);
Deencapsulation.invoke(instance, methodName, parameterTypes, methodArgs);

You need to pass in the parameterTypes if one of the args is null like this:

DataTap tap = new DataTap();
String response = null;
Class[] parameterTypes = { String.class };
Deencapsulation.invoke(tap, "parseResponse", parameterTypes, response);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top