What to Assert or expect when checked exception occurs in Mockito Junit test

Viewed 203

How to run a JUnit Test case on Checked Exception. For e.g. HttpClient execute method shows checked IOException but i am not sure what to assert/expect.

    import org.apache.http.client.HttpClient;
            import org.apache.http.client.methods.HttpPost;
            import org.apache.http.client.methods.HttpUriRequest;
        
             @Test
              public void throwIOExceptionOnHttpRequest() {
                HttpClient httpClient = mock(HttpClient.class)
                HttpUriRequest httpUriRequest = mock(HttpUriRequest.class);
          
    try{   
  when(httpClient.execute(any(HttpPost.class))).thenThrow(IOException.class);
         httpClient.execute(httpUriRequest);
                //Ideally nothing should work after this as exception is thrown
                        //fail("This will fail") // this statement will throw Assertion Error
                    }
                    catch (IOException io) {
                    
                    }
                }

If i try using expected method, this returns IOException never thrown.

 Exception thrown =
                  assertThrows(
                          IOException.class,
                          () -> {
                           when(httpClient.execute(any(HttpPost.class))).thenThrow(IOException.class);
                          });
    
          Truth.assertThat(thrown).hasMessageThat().contains("IOException");
        }
2 Answers

In your test method you only stubbed httpClient.execute method, but never called it. That is why no exception has been thrown.

On top of that:

  • it is unclear what is object under test. Mock collaborators, not object under test.
  • if you only assert on message containing "IOException" string, you may prefer to assert that it is the instance of that class.

If I correctly understood, You need annotation @Test. And you should assign field "expected" your exception class.

@Test(excepted = IOException.class)
testMethod() {
     throw new IOException();
}
Related