Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

unit testing - How do you use PHPUnit to test a function if that function is supposed to kill PHP?

Essentially I have a method of a class called killProgram, which is intended to send a hTTP redirect and then kill PHP.

How am I supposed to test this? When I run phpunit it doesn't return anything for that test, and closes completely.

Right now I'm considering having the killProgram function throw an exception which shouldn't get handled, which would allow me to assert that an exception was thrown.

Is there a better way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's obviously an old question but my suggestion would be to move the code that die()'s into a separate method that you can then mock.

As an example, instead of having this:

class SomeClass
{
    public function do()
    {
        exit(1);
        // or
        die('Message');
    }
}

do this:

class SomeClass
{
    public function do()
    {
        $this->terminate(123);
        // or
        $this->terminate('Message');
    }

    protected function terminate($code = 0)
    {
        exit($code);
    }

    // or 
    protected function terminate($message = '')
    {
        die($message);
    }
}

That way you can easily mock the terminate method and you don't have to worry about the script terminating without you being able to catch it.

Your test would look something like this:

class SomeClassTest extends PHPUnit_Framework_TestCase
{

    /**
     * @expectedExceptionCode 123
     */
    public function testDoFail()
    {
        $mock = $this->getMock('SomeClass');
        $mock->expects($this->any())
             ->method('terminate')
             ->will($this->returnCallback(function($code) {
                 throw new Exception($code);
             }));

        // run to fail
        $mock->do();
    }
}

I haven't tested the code but should be pretty close to a working state.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...