我想测试一个调用 exec()
的 php 函数,最好的方法是什么?我用它来获取gitdescribe
的结果:
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()
。知道怎么做吗?
最佳答案
如果您使用命名空间,则有一个模拟内置函数的技巧,如下所述:https://stackoverflow.com/a/5337635/664108
所以,基本上你可以用你自己的函数替换exec
,它的返回值将由你的测试指定。
关于php - 为执行 exec() 的对象创建测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15005340/