0

I have a class with couple of methods and each with a try catch block to look for any exceptions.

The code as follows:

public ResponseEntity get() {

    try {
        .....
    } catch (Exception e) {

        output = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return output;
}

and I came up with a test case using Mokito to test the above scenario but confused how to enter into catch block of the above

@Test
public void testgetAllUsers_withoutexecp() {
    when(sMock.getAll()).thenReturn(someList);
    Assert.assertTrue(result.getStatusCode() ==  HttpStatus.OK );
}
@Test(expected=NullPointerException.class)
public void testgetAllUsers_execp() {
    when(sMock.getAll()).thenReturn(null);
    Assert.assertFalse(result.getStatusCode() ==  HttpStatus.OK );

}

I tried to raise a NullPointerException but still the catch block is left out in codecoverage (by which I assume it is not been tested). please help me to write a Junit test case for this to enter exception. I am very new to all these topics.

jamuna
  • 93
  • 1
  • 2
  • 10

2 Answers2

3

You can raise exception using thenThrow clause of Mockito:

when(serviceMock.getAllUser()).thenThrow(new NullPointerException("Error occurred"));

and then assert like this:

Assert.assertTrue(result.getStatusCode() ==  HttpStatus.INTERNAL_SERVER_ERROR);
Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29
0

Expecting NullPointerException makes no sense. This will never happen, because you catch exceptions.

Instead, test for AppConstants.ERROR_MESSAGE9 and HttpStatus.INTERNAL_SERVER_ERROR

mentallurg
  • 4,967
  • 5
  • 28
  • 36