我很好奇指定处理文件操作的类的最佳方式。
假设我有一个虚构的类,其方法duplicate
的工作是复制文件的内容。
<?php
class FileOperator
{
public function duplicate($filename)
{
$content = file_get_contents($filename);
file_put_contents($filename, $content.$content);
}
}
我知道我可以使用 vfsStream 之类的东西来断言更改,而无需触及实际的文件系统(至少使用 PHPUnit 中的断言)。
我如何在规范中断言?还是会采用不同的方法?
另外,我知道我可能想将该功能提取到另一个类中并使用 Spy 来断言 FileOperator 正确调用了它的依赖项,但是我仍然必须指定该适配器类,以及我的问题仍然存在。
谢谢。
最佳答案
这更像是功能测试而不是单元测试,因此在这种情况下很难使用 phpspec。
如果你坚持,我有两个选择。
如果你碰巧也需要一个方法来获取文件内容,你可以这样写你的规范:
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
use PhpSpec\ObjectBehavior;
class FileOperatorSpec extends ObjectBehavior
{
/**
* @var vfsStreamDirectory
*/
private $workDir;
function let()
{
$this->workDir = vfsStream::setup('workDir');
}
function it_duplicates_a_content_in_a_file()
{
$this->createFile('foo', 'bar');
$this->duplicate('vfs://workDir/foo');
$this->read('vfs://workDir/foo')->shouldReturn('barbar');
}
private function createFile($path, $content)
{
$file = vfsStream::newFile($path);
$file->setContent($content);
$this->workDir->addChild($file);
}
}
或者,您可以使用 expect helper :
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
use PhpSpec\ObjectBehavior;
class FileOperatorSpec extends ObjectBehavior
{
/**
* @var vfsStreamDirectory
*/
private $workDir;
function let()
{
$this->workDir = vfsStream::setup('workDir');
}
function it_duplicates_a_content_in_a_file()
{
$this->createFile('foo', 'bar');
$this->duplicate('vfs://workDir/foo');
expect(file_get_contents('vfs://workDir/foo'))->toBe('barbar');
}
private function createFile($path, $content)
{
$file = vfsStream::newFile($path);
$file->setContent($content);
$this->workDir->addChild($file);
}
}
关于phpspec 测试文件内容/文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24160378/