【问题标题】:How to test includes (PHPUnit / PHPSpec / SimpleTest / etc)如何测试包括(PHPUnit / PHPSpec / SimpleTest / 等)
【发布时间】:2014-09-22 04:02:30
【问题描述】:

假设我有以下课程:

class FooBar
{
    public function getArrayFromFile($file)
    {
        if (!is_readable($file)) {
            return [];
        }

        return include $file;
    }
}

假设 $file 包含以下内容:

return [
...
];

如何测试它?具体来说,如何为“包含”创建双精度。

【问题讨论】:

  • 我认为你应该存根这个方法,因为它依赖于外部文件。
  • 举个例子会非常有帮助……不仅对我,对其他可能有同样困境的人。

标签: php unit-testing phpunit simpletest phpspec


【解决方案1】:

你可以通过几种方式做到这一点。

您可以创建一个包含一些内容的测试文件并在您的测试中使用该文件。这可能是最简单的,但这意味着为了让您的测试正常工作,您需要将此文件放在套件中。

为了避免跟踪测试文件,您可以模拟文件系统。 PHPUnit 文档推荐使用vfsStream。通过这种方式,您可以创建一个假文件并在您的方法中使用它。这也将更容易设置权限,以便您可以测试is_readable 条件。

http://phpunit.de/manual/current/en/phpunit-book.html#test-doubles.mocking-the-filesystem

所以在 PHPUnit 中你的测试应该是这样的:

public function testGetArrayFromFile() {
    $root = vfsStream::setup();
    $expectedContent = ['foo' => 'bar'];
    $file = vfsStream::newFile('test')->withContent($expectedContent);
    $root->addChild($file);

    $foo = new FooBar();
    $result = $foo->getArrayFromFile('vfs://test');

    $this->assertEquals($expectedContent, $result);
}

public function testUnreadableFile() {
    $root = vfsStream::setup();

    //2nd parameter sets permission on the file.
    $file = vfsStream::newFile('test', 0000); 
    $root->addChild($file);

    $foo = new FooBar();
    $result = $foo->getArrayFromFile('vfs://test');

    $this->assertEquals([], $result);
}

【讨论】:

  • 谢谢伙计,我明天试试。我的印象是您可能不会将流用于“包含”。
  • 我的主要问题是为“include”创建一个双精度,像 is_readable 这样的原生 PHP 函数可以轻松加倍。
  • 主要思想是不要太尝试创建该功能的双倍。文件的内容如何返回并不完全重要,只是它们被返回。你想测试你的代码在做什么,而不是它是怎么做的。
  • @Schleis 我认为测试这个函数有点毫无意义,因为它总是会返回并且它将是数组,如果基于文件,我认为它将是动态的,因此我认为它应该被排除在测试之外。
  • @DaGhostmanDimitrov 给定文件,根据需要返回内容或空数组。这不是没有意义的,测试很简单。如果要强制始终返回数组,您现在还可以修改功能。
猜你喜欢
  • 2014-03-31
  • 2012-08-18
  • 1970-01-01
  • 2015-08-25
  • 2016-07-10
  • 2010-09-07
  • 2015-02-14
  • 2015-02-18
  • 2018-08-28
相关资源
最近更新 更多