Я новичок в phpspec и пытаюсь создать фиктивный конвертер для учебных целей, но я застрял с Вызов функции-члена на необъектнойт ошибка
Вот мой код:
Конвертировать класс
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;
}
Класс ConvertHandler
public function getConverter($format)
{
$class = "AppBundle\Service\Converter\\".ucfirst($format).'Converter';
if (class_exists($class)) {
return new $class();
} else {
throw new \Exception();
}
}
Класс XmlConverter
public function convert(array $data)
{
return str_replace(PHP_EOL, '', TypeConverter::toXml($data));
}
Этот код работает. Возвращает строку в формате XML.
Сейчас тесты:
Класс ConvertSpec
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
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
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: вызов функции-члена convert () для необъекта в /var/www/phpSpecTest/src/AppBundle/Service/Convert.php в строке 25
Я уже пытаюсь исправить это на второй день, и ищу решение в Интернете. Но все еще не могу найти решение. Любое предложение будет оценено.
Вы не издевались ConverterHandler->getConverter()
метод в вашем let
Спец метод. Это должно быть как:
function let(ConvertHandler $handler) {
$xmlConverter = new XmlConverter(); // OR mock it :)
$handler->getConverter(Argument::any())->shouldReturn($xmlConverter);
$this->beConstructedWith($handler);
}
Других решений пока нет …