1

Here is my code for 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);

Here I want to test the IOException for response.sendRedirect(locationURI);

I cannot use Mockito when feature as it shows void method cannot be used.

@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);

Is there anyway I can throw IOException and test for send redirect? I want to test the IOException and IllegalStateException that sendRedirect method throws.

dur
  • 15,689
  • 25
  • 79
  • 125
Jasmine
  • 135
  • 3
  • 16
  • 1
    You can do something like: `doThrow(IOException.class).when(mockResponse).sendRedirect("locationURI");`. Take a look at the [documentation](http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#12). – António Ribeiro Apr 23 '16 at 15:33

1 Answers1

1

You can use Mockito with void methods.

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

In the same way you can use doThrow(new IOException())

Sergii Bishyr
  • 8,331
  • 6
  • 40
  • 69
  • I used this but it doesn't throw IOException. The expected IOException shows error – Jasmine Apr 23 '16 at 15:37
  • Make sure that in you test `.sendRedirect("locationURI")` is called. I rather suggest to mock in this way `doThrow(IOException.class).when(mockResponse).sendRedirect(anyString());` and use `verify` to check passed argument. – Sergii Bishyr Apr 23 '16 at 15:41
  • Worked....Awesome..Thank you so much – Jasmine Apr 23 '16 at 16:16