asserts after expectException not failing as expected

Re: asserts after expectException not failing as expected

by Andrew Lyons -
Number of replies: 0
Picture of Core developers Picture of Moodle HQ Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers Picture of Testers

Yes, that is is expected. When the exception happens, the code stops running. The cal to expectException tells the test runner that it should not fail if an exception is thrown, as long as it matches the information it was told.

The exception has still happened, and has therefore stopped the code.

Think of it this way:

foreach ($this->getTests() as $testName) {
    try {
        $this->$testName();
        if ($this->expectationExpected()) {
            return $this->fail("Exception expected but not thrown");
        }
        return $this->pass();
    } catch (\Exception $e) {
        if ($this->exceptionExpected()) {
            if (get_class($e) !== $this->getExpectedExceptionClass()) {
                return $this->fail("Expected a class of ... but got ...");
            }
            if ($expectedMessage = $this->getExceptionMessage()) {
                if ($e->getMessage() !== $expectedMessage) {
                    return $this->fail("Incorrect message. Expected {$expectedMessage} but got ...");
                }
                return $this->pass();
        } else {
            $this->fail("Exception thrown when it was not expected");
        }
    }
}

This is just a simplified version of what actually happens in https://github.com/sebastianbergmann/phpunit/blob/master/src/Runner/PhptTestCase.php#L112

Andrew