phpunit-testingsingletonsimpletestfatal-error

PHP Unit Tests: Is it possible to test for a Fatal Error?


FWIW I'm using SimpleTest 1.1alpha.

I have a singleton class, and I want to write a unit test that guarantees that the class is a singleton by attempting to instantiate the class (it has a private constructor).

This obviously causes a Fatal Error:

Fatal error: Call to private FrontController::__construct()

Is there any way to "catch" that Fatal Error and report a passed test?


Solution

  • No. Fatal error stops the execution of the script.

    And it's not really necessary to test a singleton in that way. If you insist on checking if constructor is private, you can use ReflectionClass:getConstructor()

    public function testCannotInstantiateExternally()
    {
        $reflection = new \ReflectionClass('\My\Namespace\MyClassName');
        $constructor = $reflection->getConstructor();
        $this->assertFalse($constructor->isPublic());
    }
    

    Another thing to consider is that Singleton classes/objects are an obstacle in TTD since they're difficult to mock.