Skip to content
This repository was archived by the owner on Aug 29, 2023. It is now read-only.

issue.exit

Edson Medina edited this page Jul 7, 2017 · 8 revisions

Exit (or die)

class foo
{
    public function bar ()
    {
        // ...
  
        exit(); 
    }
}

Why is this a testing issue?

Pretty self-explanatory. If a method calls exit() or die() the execution stops immediately and the test doesn't run.

Possible refactorings

Don't use it

Use conditionals instead. If the conditions are not met, nothing happens and the script ends normally.

Use exceptions instead

 throw new Exception ('Fatal error');

If you really need to use exit() (ie: for a CLI script return value)

Write a wrapper method.

class foo
{
    public function bar ()
    {
        // ...
  
        $this->exitApp();
    }
  
    public function exitApp ($code);
    {
        // this method will be untestable, but
        // it can be mocked to test other methods
        // that depend on it

        exit ($code);
    }
}

While this sounds silly, it allows you to unit test ->bar() with a fake ->exitApp() method, without breaking the execution.