为什么phpspec没有看到来自静态构造函数的对象的shouldBeLike?

时间:2016-11-10 20:31:09

标签: php phpspec

我试图在phpspec中使用静态构造函数来规范值对象,问题是shouldBeLike是未定义的方法。从times方法返回的对象是新的Money,因此我不知道出了什么问题......

MoneySpec:

<?php

namespace spec;

use Money;
use PhpSpec\ObjectBehavior;

class MoneySpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType(Money::class);
    }

    function it_multiplies()
    {
        $five = Money::dollar(5);
        $five->times(2)->shouldBeLike(Money::dollar(5));
        $five->times(3)->shouldBeLike(Money::dollar(6));
    }
}

货币:

<?php

class Money
{
    private $amount;

    private function __construct($amount)
    {
        $this->amount = $amount;
    }

    public static function dollar($amount)
    {
        return new Money($amount);
    }

    public function times($multiplier)
    {
        return new Money($this->amount * $multiplier);
    }

    public function getAmount()
    {
        return $this->amount;
    }
}

2 个答案:

答案 0 :(得分:1)

对于命名的静态构造函数,您需要使用beConstructedThrough(或者描述的较短语法之一)。例如,根据您的情况:

function it_multiplies()
{
    $this->beConstructedThrough('dollar', [5]);
    $this->times(2)->shouldBeLike(Money::dollar(5));
    $this->times(3)->shouldBeLike(Money::dollar(6));
}

答案 1 :(得分:0)

因为你没有定义它......我在代码中看不到它