我有一个工厂类,它根据给定文件的扩展名返回编写器策略:
public static function getWriterForFile($file)
{
// create file info object
$fileInfo = new \SplFileInfo($file);
// check that an extension is present
if ('' === $extension = $fileInfo->getExtension()) {
throw new \RuntimeException(
'No extension found in target file: ' . $file
);
}
// build a class name using the file extension
$className = 'MyNamespace\Writer\Strategy\\'
. ucfirst(strtolower($extension))
. 'Writer';
// attempt to get an instance of the class
if (!in_array($className, get_declared_classes())) {
throw new \RuntimeException(
'No writer could be found for the extension: ' . $extension
);
}
$instance = new $className();
$instance->setTargetFile($file);
return $instance;
}
我所有的策略都实现了相同的接口,例如:
class CsvWriter implements WriterStrategyInterface
{
public function setTargetFile($file)
{
...
}
public function writeLine(array $data)
{
...
}
public function flush()
{
...
}
}
我希望能够使用虚拟扩展来测试此方法,以便我的测试不依赖于任何现有的特定策略。我尝试使用设置的类名为接口创建一个模拟,但这似乎没有声明模拟类名:
public function testExpectedWriterStrategyReturned()
{
$mockWriter = $this->getMock(
'MyNamespace\Writer\Strategy\WriterStrategyInterface',
array(),
array(),
'SssWriter'
);
$file = 'extension.sss';
$writer = MyNamespace\Writer\WriterFactory::getWriterForFile($file);
$this->assertInstanceOf('MyNamespace\Writer\Strategy\WriterStrategyInterface', $writer);;
}
有什么办法让我为工厂加载一个模拟编写器策略,或者我应该重构工厂方法以使其更具可测试性?