如何对ServletResponse Java进行单元测试
以下是我的servlet代码:如何对ServletResponse Java进行单元测试,java,servlets,junit,mockito,ioexception,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.se
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
。您可以将Mockito
与void
方法一起使用
doNothing().when(mock).voidMethod();
同样,您可以使用doThrow(new IOException())
您可以执行类似的操作:doThrow(IOException.class).when(mockResponse.sendRedirect(“locationURI”)代码>。看看这个。我用过这个,但它没有抛出IOException。预期的IOException显示Error确保在测试中调用了.sendRedirect(“locationURI”)
。我建议用这种方式模拟doThrow(IOException.class).when(mockResponse.sendRedirect(anyString())
并使用验证
检查已传递的参数。有效…太棒了。非常感谢