Hướng dẫn dùng assert exception trong PHP

TLDR; scroll to: Use PHPUnit's Data Provider

Nội dung chính

  • How to test multiple Exceptions?
  • Split multiple exceptions into separate tests:
  • Catch an exception and check it with an assertion
  • Use PHPUnit's Data Provider
  • Testing Exceptions Gotchas
  • exception of type "TypeError"
  • exception of type "TypeError" again

Nội dung chính

  • How to test multiple Exceptions?
  • Split multiple exceptions into separate tests:
  • Catch an exception and check it with an assertion
  • Use PHPUnit's Data Provider
  • Testing Exceptions Gotchas
  • exception of type "TypeError"
  • exception of type "TypeError" again

Nội dung chính

  • How to test multiple Exceptions?
  • Split multiple exceptions into separate tests:
  • Catch an exception and check it with an assertion
  • Use PHPUnit's Data Provider
  • Testing Exceptions Gotchas
  • exception of type "TypeError"
  • exception of type "TypeError" again

Nội dung chính

  • How to test multiple Exceptions?
  • Split multiple exceptions into separate tests:
  • Catch an exception and check it with an assertion
  • Use PHPUnit's Data Provider
  • Testing Exceptions Gotchas
  • exception of type "TypeError"
  • exception of type "TypeError" again

Nội dung chính

  • How to test multiple Exceptions?
  • Split multiple exceptions into separate tests:
  • Catch an exception and check it with an assertion
  • Use PHPUnit's Data Provider
  • Testing Exceptions Gotchas
  • exception of type "TypeError"
  • exception of type "TypeError" again

PHPUnit 9.5 offers following methods to test exceptions:

$this->expectException[string $exceptionClassName];
$this->expectExceptionCode[int|string $code];
$this->expectExceptionMessage[string $message];
$this->expectExceptionMessageMatches[string $regularExpression];
$this->expectExceptionObject[\Exception $exceptionObject];

However the Documentation is vague about the order of any of the above methods in the test code.

If you get used to using assertions for example:

Chủ Đề