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.

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.