Try catch in a JUnit test

前端 未结 7 591
悲哀的现实
悲哀的现实 2020-12-04 23:21

I\'m writing unit tests for an application that already exists for a long time. Some of the methods I need to test are build like this:

public void someMetho         


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 23:53

    There are two main rules on how to process exceptions at Junit testers:

    1. If the exception was originated into the tested code:

      • If it was expected, declare it in the expected attribute of the Test annotation. Or, if further checks should be done on the exception object itself, catch it and ignore it. (In this case, there must be also a call to Assert.fail at the end of the try block, to indicate that the expected exception was not produced).
      • If it was not expected, catch it and execute Assert.fail. (A previous call to Exception.printStackTrace is also useful).
    2. If the exception was not originated into the tested code or it is not interesting to the test (for example, most of the IOExceptions are produced at network level, before the test could even be completed), rethrow it at the throws clause.

    Why you should expect an exception in the tester? Remind: You should code one test method for every possible result on the tested code (in order to achieve a high code coverage): In your case, one method that must return successfully, and at least another one that must produce an Exception.

提交回复
热议问题