Php规范。当 mock 必须 return 一个对象时调用非对象的成员函数

PhpSpec. Call to a member function on a non-object when mock must return an object

我是 phpspec 的新手,正在尝试创建用于学习目的的虚拟转换器,但我坚持使用 在非对象上调用成员函数 t 错误

这是我的代码:

兑换class

private $supportedFormats = ['xml', 'json'];
private $handler;

public function __construct(ConvertHandler $handler)
{
    $this->handler = $handler;
}

public function convert(array $data, $format)
{
    if (!$this->shlouldBeSupportedFormat($format)) {
        throw new \Exception();
    }
    $converter = $this->handler->getConverter($format);

    return $converter->convert($data);
}

public function shlouldBeSupportedFormat($format)
{
    if (!in_array($format, $this->supportedFormats)) {
        return false;
    }

    return true;
}

ConvertHandlerclass

public function getConverter($format)
{
    $class = "AppBundle\Service\Converter\".ucfirst($format).'Converter';
    if (class_exists($class)) {
        return new $class();
    } else {
        throw new \Exception();
    }
}

XmlConverter class

public function convert(array $data)
{
    return str_replace(PHP_EOL, '', TypeConverter::toXml($data));
}

此代码有效。它 returns 格式为 XML 的字符串。

现在测试:

ConvertSpec class

function let(ConvertHandler $handler) {
    $this->beConstructedWith($handler);
}

function its_convert_function_should_be_valid()
{
    $this->shouldThrow('Exception')->during('convert', ['sadsa','xml']);
    $this->shouldThrow('Exception')->during('convert', [[],'bad_format']);
}

function it_should_check_if_support()
{
    $this->shlouldBeSupportedFormat('xml')->shouldReturn(true);
    $this->shlouldBeSupportedFormat('bad_format')->shouldReturn(false);
}

function it_should_covert_to_xml(ConvertHandler $handler)
{
    $this->convert(['test' => 'test'], 'xml')->shouldBeString();
    $handler->getConverter('xml')->shouldBeCalled();
}

ConvertHandlerSpec class

function its_get_converter_shouldBe_valid()
{
    $this->shouldThrow('Exception')->during('getConverter', ['wrong_format']);
}

function it_should_return_converter()
{
    $this->getConverter('xml')->shouldReturnAnInstanceOf('AppBundle\Service\Converter\XmlConverter');
}

XmlConverterSpec class

function it_should_implement()
{
    $this->shouldImplement('AppBundle\Service\Converter\ConverterInterface');
}
function it_should_convert()
{
    $this->convert(['test'=>'test'])->shouldBeString();
    $this->convert(['test'=>'test'])->shouldReturn(
        '<?xml version="1.0" encoding="utf-8"?><root><test>test</test></root>'
        );
}

我 运行 测试时出错: PHP 致命错误:在第 25[=17= 行 /var/www/phpSpecTest/src/AppBundle/Service/Convert.php 的非对象上调用成员函数 convert() ]

我已经在第二天尝试修复它,并在网上寻找解决方案。但仍然找不到 solution.Any 建议将不胜感激。

您还没有在 let 规范方法中模拟 ConverterHandler->getConverter() 方法。它应该是这样的:

function let(ConvertHandler $handler) {
    $xmlConverter = new XmlConverter(); // OR mock it :)
    $handler->getConverter(Argument::any())->shouldReturn($xmlConverter);
    $this->beConstructedWith($handler);
}