J-Unit Test: Make static void method in final class throw exception

不羁岁月 提交于 2019-12-13 06:36:25

问题


I am writing J-Unit Tests for my project and now this problem occured:

I am testing a servlet which uses a Utility class (class is final, all methods are static). The used method returns void and can throw an

IOException (httpResponse.getWriter).

Now I have to force this exception...

I have tried and searched a lot, but all the solutions I found did not worked, because there was no combination of final, static, void, throw.

Has anyone did this before?

EDIT: Here is the code snippet

Servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
    String action = request.getParameter("action");
    if (action.equals("saveRule")) {
        // Some 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 {
    // Some Code
    response.getWriter().write(new Gson().toJson(message));

}

}

Test Method:

@Test
public void doPostIOException () {
    // Set request Parameters
    when(getMockHttpServletRequest().getParameter("action")).thenReturn("saveRule");
    // Some more code
    // Make TOMAMappingUtils.evaluateTextToRespond throw IOExpection to jump in Catch Block for line coverage
    when(TOMAMappingUtils.evaluateTextToRespond(getMockHttpServletResponse(), anyString())).thenThrow(new IOException()); // This behaviour is what i want
}

So as you can see, i want to force the Utils method to throw an IOException, so i get in the catch block for a better line coverage.


回答1:


To mock final class, First add it in prepareForTest.

@PrepareForTest({ TOMAMappingUtils.class })

Then mock as static class

PowerMockito.mockStatic(TOMAMappingUtils.class);

Then set expectation as 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());


来源:https://stackoverflow.com/questions/31334032/j-unit-test-make-static-void-method-in-final-class-throw-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!