how to handle exceptions in junit

前端 未结 4 1915
鱼传尺愫
鱼传尺愫 2020-12-09 08:14

I wrote some test cases to test some method. But some methods throw an exception. Am I doing it correctly?

private void testNumber(String word, int number) {         


        
4条回答
  •  失恋的感觉
    2020-12-09 08:47

    You don't need to catch the exception to fail the test. Just let it go (by declaring throws) and it will fail anyway.

    Another case is when you actually expect the exception, then you put fail at the end of try block.

    For example:

    @Test
    public void testInvalidNumber() {
      try {
          String dummy = service.convert(-1));
          Assert.fail("Fail! Method was expected to throw an exception because negative numbers are not supported.")
      } catch (OutOfRangeException e) {
          // expected
      }
    }
    

    You can use this kind of test to verify if your code is properly validating input and handles invalid input with a proper exception.

提交回复
热议问题