PhpSpec - 用另一个模拟参数

时间:2016-06-26 13:10:11

标签: php phpspec prophecy

我想知道可以忽略方法中的Exception并强制使用willReturn方法吗?

我有一个例子:

理论上,Transformer必须与实体具有相同的名称(通过this->getClassName) 但在这种情况下,我该怎么办,因为我的SimpleEntityTransformerInterface不一样。

class JsonViewTransformer
{
    private $transformers = [];

    public function testTransformer(View $view)
    {
        $entity = $view->getData();
        $this->getTransformerFromEntity($entity);
    }

    public function addTransformer(TransformerInterface $transformer)
    {
        $this->transformers[$this->getClassName($transformer)] = $transformer;
    }

    private function getTransformerFromEntity($entity)
    {
        $entityName = $this->getClassName($entity);

        if (!array_key_exists($entityName, $this->transformers)) {
            throw new ClassNotFoundException(sprintf('%s does not exist', $entityName), new \ErrorException());
        }

        return $this->transformers[$entityName];
    }

    private function getClassName($object)
    {
        $FQCNObject = get_class($object);
        $objectName = substr($FQCNObject, strrpos($FQCNObject, '\\') + 1);

        return $objectName;
    }
}

在测试文件中:

function it_returns_json_from_tranformer(View $view, SimpleEntity $entity, TransformerInterface $transformer)
{
    $entity->getId()->willReturn(1);
    $entity->getName()->willReturn('foo');
    $entity->getAge()->willReturn(42);

    $transformer->transform($entity)->willReturn([
        'id',
        'name',
        'age',
    ]);

    $view->getData()->willReturn($entity);

    $this->addTransformer($transformer);
    $this->testTransformer($view);
}

所以我收到了以下错误消息:

  15  - it returns json from tranformer
      exception <label>[exc:Symfony\Component\Debug\Exception\ClassNotFoundException("P1 does not exist")]</label> has been thrown.

您对此类问题有所了解吗?

0 个答案:

没有答案