如何测试使用PHPSpec创建项的类


How to test class which create items using PHPSpec

我有一个主要针对这个的类

$newItem = new SeriesDiscountDecorator($item);
$cart->remove($item);
$cart->add($newItem);

我的规格看起来像

$decoratedItem1->beConstructedWith([$item1]);
$cart->add($decoratedItem1)->shouldBeCalled();

但PHPSpec表示,由于参数错误,没有进行正确的$cart->add调用。事实上,我的$decoratedItem与Cart类创建的对象不同。如何写出这样的规范?

PHPSpec返回:

method call:
    - add(Domain'Discount'Decorator'SeriesDiscountDecorator:000000006b0917e60000000063743658 Object (
        'decoratedItem' => Double'ItemInterface'P66:000000006b0917a60000000063743658 Object (
        'objectProphecy' => Prophecy'Prophecy'ObjectProphecy Object (*Prophecy*)
          )
      ))
    on Double'Domain'Cart'Cart'P65 was not expected, expected calls were:
        - add(exact(Double'Domain'Discount'Decorator'SeriesDiscountDecorator'P69:000000006b0917f90000000063743658 Object (
        'objectProphecy' => Prophecy'Prophecy'ObjectProphecy Object (*Prophecy*)
              'decoratedItem' => PhpSpec'Wrapper'Collaborator:000000006b0917b30000000063743658 Object (
        'prophecy' => Prophecy'Prophecy'ObjectProphecy Object (*Prophecy*)
              )
        )))
$cart->add(SeriesDiscountDecorator::class)->shouldBeCalled();

似乎是测试它的唯一方法,只要你在指定的类中实例化对象,并且不返回它

这是非常古老的,但使用phpspec 2.5.8.我能够在协作器上使用getWrappedObject()方法实现这一点。所以规格看起来是这样的:

$decoratedItem1->beConstructedWith([$item1]);
$cart->add($decoratedItem1->getWrappedObject())->shouldBeCalled();