我正在为我的项目编写J-Unit Tests,现在出现了这个问题:
我正在测试一个servlet,它使用一个实用程序类(类是最终的,所有的方法是静态的)。使用的方法返回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类:
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块以获得更好的行覆盖率。
要模拟最终类,首先将其添加到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());