4

我正在尝试将 let 函数与标量值一起使用。我的问题是价格是双倍的,我希望是整数 5。

function let(Buyable $buyable, $price, $discount)
{
    $buyable->getPrice()->willReturn($price);
    $this->beConstructedWith($buyable, $discount);
}

function it_returns_the_same_price_if_discount_is_zero($price = 5, $discount = 0) {
    $this->getDiscountPrice()->shouldReturn(5);
}

错误:

✘ it returns the same price if discount is zero
expected [integer:5], but got [obj:Double\stdClass\P14]

有没有办法使用 let 函数注入 5?

4

2 回答 2

6

在 PhpSpec 中,任何出现在let(),letgo()it_*()方法的参数中的都是测试替身。它不适用于标量。

PhpSpec 使用反射从类型提示或@param注释中获取类型。然后它创建一个带有预言的假对象并将其注入到一个方法中。如果找不到类型,它将创建一个假的\stdClass. 与类型Double\stdClass\P14无关。double这是一个测试替身

您的规格可能如下所示:

private $price = 5;

function let(Buyable $buyable)
{
    $buyable->getPrice()->willReturn($this->price);

    $this->beConstructedWith($buyable, 0);
}

function it_returns_the_same_price_if_discount_is_zero() 
{
    $this->getDiscountPrice()->shouldReturn($this->price);
}

虽然我更愿意包含与当前示例相关的所有内容:

function let(Buyable $buyable)
{
    // default construction, for examples that don't care how the object is created
    $this->beConstructedWith($buyable, 0);
}

function it_returns_the_same_price_if_discount_is_zero(Buyable $buyable) 
{
    // this is repeated to indicate it's important for the example
    $this->beConstructedWith($buyable, 0);

    $buyable->getPrice()->willReturn(5);

    $this->getDiscountPrice()->shouldReturn(5);
}
于 2014-02-09T22:28:50.367 回答
-2

投射5(double)

$this->getDiscountPrice()->shouldReturn((double)5);

或使用“比较匹配器”

$this->getDiscountPrice()->shouldBeLike('5');
于 2014-01-28T21:06:49.843 回答