pl中的phpspec标量值

时间:2014-01-28 00:18:28

标签: php unit-testing phpspec

我正在尝试使用带有标量值的let函数。 我的问题是价格是双倍的,我预计是一个整数。

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?

2 个答案:

答案 0 :(得分:6)

在PhpSpec中,let()letgo()it_*()方法的参数中的任何内容都是测试双重。它并不意味着与标量一起使用。

PhpSpec使用反射从类型提示或@param注释中获取类型。然后它创建一个带有预言的虚假对象并将其注入方法中。如果找不到类型,则会创建假\stdClassDouble\stdClass\P14double类型无关。这是一个test 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);
}

答案 1 :(得分:-2)

5投放到(double)

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

或使用"comparison matcher"

$this->getDiscountPrice()->shouldBeLike('5');