php - 为执行 exec() 的对象创建测试

标签 php unit-testing phpunit

我想测试一个调用 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/

相关文章:

java - 如何检查异常的原因是否与异常类型匹配

session - 使用 Silex SessionServiceProvider 时 PHPUnit 失败

php - 将 HTML 保存到 MySQL 警告 : #1265 Data truncated for column

PHP 撤消按钮

php - 将复选框列表放在可调整大小的区域

node.js - 使用 MongoDB 进行单元测试查询

php - SELECT COUNT(*) FROM 'accounts' WHERE role = 'engineer' 使用 symfony1.4 获取总行数

unit-testing - TFS 构建和测试影响

database - 在 PHPUnit 测试中从 SQL 文件加载模式

unit-testing - CodeIgniter 2.0/PHPUnit 已经出现了吗?