sebastianbergmann/phpunit · error · AssertionFailedError

Failed asserting that exception with message matching "%s" i

Error message

Failed asserting that exception with message matching "%s" is thrown

What it means

Thrown by ExceptionExpectation::assertWasRaised() when expectExceptionMessageMatches() set a regular expression expectation but no exception was raised during the test. Since assertWasRaised() only runs when the test body completed without throwing, there is no message to match and PHPUnit reports the failed regex expectation.

Source

Thrown at src/Framework/TestCase/ExceptionExpectation.php:163

        if ($this->expectedException !== null) {
            Assert::assertThat(
                null,
                new ExceptionConstraint($this->expectedException),
            );
        } elseif ($this->expectedMessageConstraint !== null) {
            $test->addToAssertionCount(1);

            throw new AssertionFailedError(
                sprintf(
                    'Failed asserting that exception with message %s "%s" is thrown',
                    $this->expectedMessageConstraint instanceof ExceptionMessageIs ? 'is' : 'containing',
                    $this->expectedMessage,
                ),
            );
        } elseif ($this->expectedMessageRegularExpression !== null) {
            $test->addToAssertionCount(1);

            throw new AssertionFailedError(
                sprintf(
                    'Failed asserting that exception with message matching "%s" is thrown',
                    $this->expectedMessageRegularExpression,
                ),
            );
        } elseif ($this->expectedCode !== null) {
            $test->addToAssertionCount(1);

            throw new AssertionFailedError(
                sprintf(
                    'Failed asserting that exception with code "%s" is thrown',
                    $this->expectedCode,
                ),
            );
        }
    }
}

View on GitHub (pinned to f123cdb2a2)

Solutions

  1. Make the test drive the code into the branch that throws
  2. Update or remove the expectation if the code intentionally no longer throws

Example fix

// before
$this->expectExceptionMessageMatches('/status code \d+/');
$client->request('GET', '/health'); // returns 200, no exception

// after
$this->expectExceptionMessageMatches('/status code \d+/');
$client->request('GET', '/missing');
Defensive patterns

Strategy: validation

Prevention

When it happens

Trigger: Calling $this->expectExceptionMessageMatches('/.../') while the code under test completes without throwing any exception.

Common situations: Behavior changed so the previous error no longer occurs; the test exercises the happy path by mistake; the failing branch is behind a condition the test does not satisfy.

Related errors


AI-assisted analysis of sebastianbergmann/phpunit@f123cdb2a2 (2026-08-23). Data as JSON: /api/errors/fee0025515b3149b. Report an issue: GitHub.