我试图在phpspec中使用静态构造函数来规范值对象,问题是shouldBeLike
是未定义的方法。从times
方法返回的对象是新的Money,因此我不知道出了什么问题......
<?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;
}
}
答案 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)
因为你没有定义它......我在代码中看不到它