I am learning mockito and power mockito so forgive me if this question is dumb.
I am trying to mock the following line to throw some exception:
new ResultJSONWrapper.Success(null).toJSON();
I think I need to some how mock the constructor of success class to throw JSONException but couldn't find any solid solution to it. Can some one please give me some hints?
public abstract class ResultJSONWrapper {
private String json;
public String toJSON() {
return json;
}
static public class Success extends ResultJSONWrapper {
public Success(Object result) throws JSONException {
JSONWriter writer = new JSONStringer();
writer.object();
writer.key("status");
writer.value(HTTP_OK);
writer.key("data");
writer.value(result);
writer.endObject();
super.json = writer.toString();
}
}
}
Mockito does not allow you to mock constructors and the Power Mockito is the last thing you should use.
Since the ResultJSONWrapper
is an abstract
class you can just create your TestResultJSONWrapper
implementation that will throw JSONException
during creation and will be past to the part of the code you are testing
public class TestSuccessMock extends ResultJSONWrapper {
public TestSuccessMock (Object result) throws JSONException {
throw new JSONException();
}
}
So basically my advise here is to just not use Mockito for this purpose
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.