0

我想知道是否可以忽略Exceptionin 方法并强制使用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.

你对这类问题有想法吗?

4

0 回答 0