【发布时间】:2016-08-17 04:41:32
【问题描述】:
这是我的 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);
当功能显示 void 方法无法使用时,我无法使用 Mockito。
@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 并测试发送重定向吗?我想测试sendRedirect 方法抛出的IOException 和IllegalStateException。
【问题讨论】:
-
您可以执行以下操作:
doThrow(IOException.class).when(mockResponse).sendRedirect("locationURI");。看看documentation。
标签: java servlets junit mockito ioexception