i writing j-unit tests project , problem occured:
i testing servlet uses utility class (class final, methods static). used method returns void , can throw an
ioexception (httpresponse.getwriter).
now have force exception...
i have tried , searched lot, solutions found did not worked, because there no combination of final, static, void, throw.
has did before?
edit: here code snippet
servlet:
protected void dopost(httpservletrequest request, httpservletresponse response) throws ioexception { try { string action = request.getparameter("action"); if (action.equals("saverule")) { // code string resp = "blablabla"; tomamappingutils.evaluatetexttorespond(response, resp); } } catch (ioexception e) { tomamappingutils.requesterrorhandling(response, "ioexception", e); } }
utils class:
public final class tomamappingutils { private static final logger logger = logger.getlogger(tomamappingutils.class.getname()); private static final gson gson = new gson(); public static void evaluatetexttorespond(httpservletresponse response, string message) throws ioexception { // code response.getwriter().write(new gson().tojson(message)); } }
test method:
@test public void dopostioexception () { // set request parameters when(getmockhttpservletrequest().getparameter("action")).thenreturn("saverule"); // more code // make tomamappingutils.evaluatetexttorespond throw ioexpection jump in catch block line coverage when(tomamappingutils.evaluatetexttorespond(getmockhttpservletresponse(), anystring())).thenthrow(new ioexception()); // behaviour want } so can see, want force utils method throw ioexception, in catch block better line coverage.
to mock final class, first add in preparefortest.
@preparefortest({ tomamappingutils.class }) then mock static class
powermockito.mockstatic(tomamappingutils.class); then set expectation below.
powermockito.dothrow(new ioexception()) .when(tomamappingutils.class, membermatcher.method(tomamappingutils.class, "evaluatetexttorespond",httpservletresponse.class, string.class )) .witharguments(matchers.anyobject(), matchers.anystring()); another way:
powermockito .dothrow(new ioexception()) .when(myhelper.class, "evaluatetexttorespond", matchers.any(httpservletresponse.class), matchers.anystring());
Comments
Post a Comment