gpt4 book ai didi

java - 如何对 ServletResponse Java 进行单元测试

转载 作者:行者123 更新时间:2023-11-30 07:25:55 26 4
gpt4 key购买 nike

这是我的 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并测试发送重定向?我想测试IOExceptionIllegalStateExceptionsendRedirect方法抛出异常。

最佳答案

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

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

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

关于java - 如何对 ServletResponse Java 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36812644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com