如何单元测试ServletResponse Java

时间:2016-04-23 15:22:35

标签: java servlets junit mockito ioexception

这是我的servlet代码:

String foo = "foo";
Foo foo = Foofactory.getfoos(foo);
String locationURI;
String redirectURI = "http://" + request.getServerName() + ":" +request.getServerPort() + "/foo";
locationURI = foo.getRequestBuilder(redirectURI);
response.sendRedirect(locationURI);

我想测试IOException

response.sendRedirect(locationURI);

我无法使用Mockito功能,因为它显示无法使用void方法。

@Test(expected = IOException.class)
public void testService_CheckIOException() throws ServletException,     IOException {
    when(mockFoofactory.getfoos(Matchers.eq("foo"))).thenReturn(mockfoo);
    when(mockRequest.getServerName()).thenReturn("serverName");
    when(mockRequest.getServerPort()).thenReturn(80);
    when(mockfoo.getRequestBuilder(Matchers.eq("http://serverName:80foo")))
        .thenReturn("locationURI");
    Servlet.service(mockRequest, mockResponse);
    //This line doesn't work in mockito
    when(mockResponse).sendRedirect("locationURI")).thenThrow(IOException.class);

无论如何我可以抛出IOException并测试发送重定向吗?我想测试IOException方法抛出的IllegalStateExceptionsendRedirect

1 个答案:

答案 0 :(得分:1)

您可以Mockito方法使用void

doNothing().when(mock).voidMethod();

以同样的方式使用doThrow(new IOException())