PHPunit 文件测试

标签 php unit-testing testing tdd phpunit

我对 PHPUnit 和 TDD 比较陌生,我想知道如何测试以下代码:

class File
{
    /**
     * Write data to a given file
     * 
     * @param string $file
     * @param string $content
     * @return mixed
     */
    public function put($path, $content)
    {
        return file_put_contents($path, $content);
    }
}

如何在不实际创建文件的情况下测试文件是否已创建(显然是使用 PHPUnit)。

谢谢。

最佳答案

您可以通过使用类似 vfsStream 的虚拟文件系统来为您的单元测试模拟文件系统。带文档 here

编辑

一个例子是这样的:

class FileTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var  vfsStreamDirectory
     */
    private $root;

    /**
     * set up test environmemt
     */
    public function setUp()
    {
        $this->root = vfsStream::setup('exampleDir');
    }

    /**
     * test that the file is created
     */
    public function testFileIsCreated()
    {
        $example = new File();
        $filename = 'hello.txt';
        $content = 'Hello world';
        $this->assertFalse($this->root->hasChild($filename));
        $example->put(vfsStream::url('exampleDir/' . $filename), $content);
        $this->assertTrue($this->root->hasChild($filename));
    }
}

关于PHPunit 文件测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24499175/

相关文章:

angular - 是否可以模拟 typescript 装饰器?

unit-testing - 使用模拟类进行单元测试

javascript - 使用正则表达式替换 url 中的字符串

php - 如何保存来自 Google 的图片

php - 您为 Symfony 使用哪个单元测试框架?

unit-testing - Joomla 3.0——用于测试目的的独立应用程序

c# - 如何创建一个辅助函数来调用作为参数传递的其他函数

java - 如何使用带有 Java 的 Selenium WebDriver (Selenium 2) 在文本框中键入内容?

php - 在php中将数据从sql转换为json文件

php - 在readynas duo上运行phpmyadmin时出现"fatal error"