2

我想测试一个 php 函数调用exec(),最好的方法是什么?我用它来得到结果git describe

class Version
{
    public function getVersionString()
    {
        $result = exec('git describe --always');

        if (false !== strpos($result, 'fatal')) {
            throw new RuntimeException(sprintf(
                'Git describe returns error: %s',
                $result
            ));
        }

        return $result;
    }
}

所以我想测试命令是否被执行,当发生错误时,抛出异常(即“预期”行为和“异常”行为)。

class VersionTest extends PHPUnit_Framework_TestCase
{
    public function testVersionResultsString()
    {
        $version = new Version();
        $result  = $version->getVersionString();

        $this->assertEquals('...', $result);
    }

    public function testVersionResultHasFatalErrorThrowsException()
    {
        // trigger something that will cause the fatal
        $this->setExpectedException('RuntimeException');

        $version = new Version();
        $result  = $version->getVersionString();
    }
}

当然课程和测试实际上要复杂一些,但本质是捕捉exec()某处。知道怎么做吗?

4

1 回答 1

2

如果您使用命名空间,则有一个模拟内置函数的技巧,如下所述:https ://stackoverflow.com/a/5337635/664108

所以,基本上你可以exec用你自己的函数替换,它的返回值将由你的测试指定。

于 2013-02-21T15:04:11.233 回答