Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 414
Stephen Avatar asked Jan 20 '11 23:01

Stephen


People also ask

What errors are commonly found during unit testing?

Unit testing considerations What errors are commonly found during Unit Testing? (1) Misunderstood or incorrect arithmetic precedence, (2) Mixed mode operations, (3) Incorrect initialization, (4) Precision inaccuracy, (5) Incorrect symbolic representation of an expression.

What would occur if a fatal error was thrown in your PHP program?

Fatal errors are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place.

What is PHPUnit testing?

PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit design for unit testing systems that began with SUnit and became popular with JUnit. Even a small software development project usually takes hours of hard work.

Does unit test increase code quality?

Good unit tests create testable code, which improves quality. That code will have fewer defects, which means fewer bug fixes, for faster project completion.


2 Answers

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.

like image 139
Mchl Avatar answered Sep 19 '22 13:09

Mchl


Here's a complete code snippet of Mchl's answer so people don't have to go through the docs...

public function testCannotInstantiateExternally()
{
    $reflection = new \ReflectionClass('\My\Namespace\MyClassName');
    $constructor = $reflection->getConstructor();
    $this->assertFalse($constructor->isPublic());
}
like image 41
PressingOnAlways Avatar answered Sep 21 '22 13:09

PressingOnAlways