这是我的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
方法抛出的IllegalStateException
和sendRedirect
。
答案 0 :(得分:1)
您可以Mockito
方法使用void
。
doNothing().when(mock).voidMethod();
以同样的方式使用doThrow(new IOException())