J-Unit 测试:在 final class 中使 static void 方法抛出异常

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

我正在为我的项目编写 J-Unit 测试,现在出现了这个问题:

我正在测试一个使用 Utility class 的 servlet(class 是最终的,所有方法都是静态的)。使用的方法 returns void 并且可以抛出一个

IOException (httpResponse.getWriter).

现在我必须强制这个异常...

我已经尝试和搜索了很多,但我找到的所有解决方案都没有用,因为有 no combination of final, static, void, throw.

以前有人这样做过吗?

编辑: 这是代码片段

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);
}

}

实用程序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
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
}

如您所见,我想强制 Utils 方法抛出 IOException,因此我进入 catch 块以获得更好的行覆盖率。

要模拟决赛 class,首先将其添加到 prepareForTest

@PrepareForTest({ TOMAMappingUtils.class })

然后模拟为静态 class

PowerMockito.mockStatic(TOMAMappingUtils.class);

然后如下设置期望。

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

另一种方式:

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