TestNG: How to test for mandatory exceptions?

后端 未结 7 1761
刺人心
刺人心 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 10:06

    @Test(expectedExceptions) is useful for the most common cases:

    • You expect a specific exception to be thrown
    • You need the message of that exception to contain specific words

    Per the documentation a test will fail if no expectedException is thrown:

    The list of exceptions that a test method is expected to throw. If no exception or a different than one on this list is thrown, this test will be marked a failure.

    Here are a few scenarios where @Test(expectedExceptions) is not sufficient:

    • Your test method has several statements and only one of them is expected to throw
    • You are throwing your own type of exception and you need to make sure it matches a certain criterion

    In such cases, you should just revert to the traditional (pre-TestNG) pattern:

    try {
      // your statement expected to throw
      fail();
    }
    catch() {
      // pass
    }
    

提交回复
热议问题