J- Unit Test: Make static method void on class exception

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

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

IOException (httpResponse.getWriter).

Now I need to force this exception ...

I tried a lot and searched a lot, but all the solutions I found didn't work because I was no combination of final, static, void, throw


Has anyone done this before?

EDIT: Here is a piece of code


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:

public void doPostIOException () {
    // Set request Parameters
    // 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 ended up in a catch block for better line coverage.


source to share

1 answer

To make fun of the final class, first add it to prepareForTest


@PrepareForTest({ TOMAMappingUtils.class })


Then layout as static class



Then set your expected value below.

PowerMockito.doThrow(new IOException())
                    "evaluateTextToRespond",HttpServletResponse.class, String.class ))
    .withArguments(Matchers.anyObject(), Matchers.anyString());


Another way:

    .doThrow(new IOException())
    .when(MyHelper.class, "evaluateTextToRespond", 
             Matchers.any(HttpServletResponse.class), Matchers.anyString());




All Articles