TestNG: How to test for mandatory exceptions?

后端 未结 7 1768
刺人心
刺人心 2020-12-06 09:21

I\'d like to write a TestNG test to make sure an exception is thrown under a specific condition, and fail the test if the exception is not thrown. Is there an easy way to do

7条回答
  •  难免孤独
    2020-12-06 09:58

    I have to disagree with the the article on the nature of the testing techniques employed. The solution employs a gate, to verify if the test should succeed or fail in an intermediate stage.

    In my opinion, it is better to employ Guard Assertions, especially for such tests (assuming that the test does not turn out to be long-winded and complex, which is an anti-pattern in itself). Using guard-assertions forces you to design the SUT in either of the following ways:

    • design the method itself to provide enough information in the result on whether the invocation passed or succeeded. Sometimes, this cannot be done as the intention of the designer is to not return a result, and instead throw an exception (this can be handled in the second case).
    • design the SUT so that it's state can be verified after each significant method invocation.

    But before we consider the above possibilities, have a look at the following snippet again:

    plane.bookAllSeats();
    plane.bookPlane(createValidItinerary(), null);
    

    If the intention is to test bookPlane() and verify for execution of that method, it is better to have bookAllSeats() in a fixture. In my understanding, invoking bookAllSeats() is equivalent to setting up the SUT to ensure that the invocation of bookPlane() fails, and hence having a fixture to do the same would make for a more readable test. If the intention are different, I would recommend testing the state after every transition (as I normally would do in functional tests), to help pinpoint the original cause of failure.

提交回复
热议问题