Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...