我有一个通过命名构造函数创建文件的类,但是当我使用 phpspec 对其进行测试时,它不会创建文件。
我找不到原因,所以我想重新审视我的代码可能会有所帮助。
这是我的文件类:
<?php
namespace Acme;
class File
{
/**
* @var Path
*/
private $path;
/**
* @var FileName
*/
private $fileName;
private function __construct(Path $path, FileName $fileName)
{
$this->path = $path;
$this->fileName = $fileName;
}
public static function create(Path $path, FileName $fileName)
{
if (file_exists((string) $path . (string) $fileName)) {
throw new \DomainException('File already exists');
}
if (!touch((string) $path . (string) $fileName)) {
throw new \DomainException('Cannot create file');
}
return new self($path, $fileName);
}
}
这是我的规格:
<?php
namespace spec\Acme;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Acme\Path;
use Acme\FileName;
class FileSpec extends ObjectBehavior
{
private $testPath;
private $existingFileName = 'existingFile.extension';
private $nonExistingFileName = 'nonExistingFile.extension';
private $existingFilePath;
private $nonExistingFilePath;
function let()
{
$this->testPath = sys_get_temp_dir() . '/';
$this->existingFilePath = $this->testPath . $this->existingFileName;
$this->nonExistingFilePath = $this->testPath . $this->nonExistingFileName;
// Creating existing file
if (!touch($this->existingFilePath)) {
throw new \Exception('Cannot create existing file for testing');
}
// Removes non existing file
if (file_exists($this->nonExistingFilePath)) {
if (!unlink($this->nonExistingFilePath)) {
throw new \Exception('Cannot remove non existing file for testing');
}
}
}
function it_does_not_create_a_file_when_the_file_already_exists(Path $path, FileName $fileName)
{
$path->__toString()->willReturn($this->testPath);
$fileName->__toString()->willReturn($this->existingFileName);
$this->beConstructedThrough('create', [$path, $fileName]);
$this->shouldThrow(new \DomainException('File already exists'))->duringInstantiation();
}
function it_creates_a_new_file_if_file_does_not_exist(Path $path, FileName $fileName)
{
$path->__toString()->willReturn($this->testPath);
$fileName->__toString()->willReturn($this->nonExistingFileName);
$this->beConstructedThrough('create', [$path, $fileName]);
assert(file_exists($this->nonExistingFilePath));
}
}