【问题标题】:How to unit test ServletResponse Java [duplicate]如何对ServletResponse Java进行单元测试[重复]
【发布时间】: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);

这里我想测试IOExceptionresponse.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 方法抛出的IOExceptionIllegalStateException

【问题讨论】:

  • 您可以执行以下操作:doThrow(IOException.class).when(mockResponse).sendRedirect("locationURI");。看看documentation

标签: java servlets junit mockito ioexception


【解决方案1】:

您可以将Mockitovoid 方法一起使用。

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

同样你可以使用doThrow(new IOException())

【讨论】:

  • 我用过这个,但它不会抛出 IOException。预期的 IOException 显示错误
  • 确保在您的测试中调用了.sendRedirect("locationURI")。我宁愿建议以这种方式模拟 doThrow(IOException.class).when(mockResponse).sendRedirect(anyString()); 并使用 verify 来检查传递的参数。
  • 工作..太棒了..非常感谢
猜你喜欢
  • 1970-01-01
  • 2018-11-22
  • 1970-01-01
  • 2010-09-10
  • 1970-01-01
  • 2012-01-08
  • 2010-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多