【发布时间】:2014-07-31 00:51:39
【问题描述】:
我对 phpspec 还很陌生,但通常我会在遇到问题时找到解决方案,但这个解决方案很难。
我尝试了许多不同的方法,但没有找到解决方案。我正在使用 Symfony2。
我有一个要测试的课程:
class MyClass
{
public function getDataForChildren(MyObject $object)
{
foreach ($object->getChildren() as $child) {
$query = \json_decode($child->getJsonQuery(), true);
$data = $this->someFetcher->getData($query);
$child->setData($data);
}
return $object;
}
}
这是我的规范类的外观:
class MyClassSpec
{
function let(SomeFetcher $someFetcher)
{
$this->beConstructedWith($someFetcher);
}
function it_is_initializable()
{
$this->shouldHaveType('MyClass');
}
function it_should_get_data_for_children_and_return_object(
MyClass $object,
MyClass $child, // it means that MyClass has a self-reference to MyClass
$someFetcher
)
{
$query = '{"id":1}';
$returnCollection = new ArrayCollection(array($child));
$object->getChildren()->shouldBeCalled()->willReturn($returnCollection);
$child->getJsonQuery()->shouldBeCalled()->willReturn($query);
$someFetcher->getData($query)->shouldBeCalled();
$this->getDataForChildren($object);
}
}
在运行 phpspec 后,我得到了这个错误:
warning: json_decode() expects parameter 1 to be string, object given in
我不知道如何解决这个问题。如果有人有线索,请帮忙。
【问题讨论】:
-
警告很清楚,
$child->getJsonQuery()是一个对象,json_decode 需要字符串,看看类中是否有类似$child->getJsonQuery()->jsonString()或类似的方法 -
有:
$child->getJsonQuery(),它被存根:$child->getJsonQuery()->shouldBeCalled()->willReturn($query);。$child是一个实体,而 jsonQuery 是其中的一个字段,所以当$child->getJsonQuery()被调用时,我认为它会返回字符串(因为我将它存根)。
标签: php symfony testing phpspec