How do I test for an exact Exception message, rather than a substring, with PHPUnit?

后端 未结 6 1758
难免孤独
难免孤独 2021-01-12 07:14

According to the PHPUnit Documentation on @expectedExceptionMessage, the string must only be a substring of the actual Exception thrown.

In

6条回答
  •  渐次进展
    2021-01-12 07:44

    I normally do not worry about the text of the exception, but that the exception itself is thrown, so that an @expectedException can be used, and even a Data Provider for most error scenarios.

    The other change I make then is to do the tests (a < b) in a different function, and if a failure occurs, throw the exception, instead of combining them all and looking at the text. The different functions can then be tested on their own as well.

    From reading the PHPUnit manual, even the error thrown on assert uses the word 'contains', so it implies that it is a substring match. The same manual suggests writing the tests as you did above, so I believe that as long as you want to check the exception text, then according to the samples in the PHPUnit manual, you need to write the tests as you did.

    I would also caution from comparing the actual text, in case you add multiple language support in the future, the test will need to then understand the different languages/sentences returned. Simply checking the exception is thrown, will not suffer this problem.

提交回复
热议问题