我正在为我的项目编写 J-Unit Tests ,现在出现了这个问题:
我正在测试一个使用Utility类的servlet(类是final,所有方法都是静态的)。 used方法返回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);
}
}
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
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块以获得更好的线覆盖。
答案 0 :(得分:0)
要模拟最终课程,请先将其添加到prepareForTest
。
@PrepareForTest({ TOMAMappingUtils.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());