【问题标题】:phpspec scalar value in letlet 中的 phpspec 标量值
【发布时间】:2014-01-28 00:18:27
【问题描述】:

我正在尝试使用带有标量值的 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?

【问题讨论】:

    标签: php unit-testing phpspec


    【解决方案1】:

    在 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);
    }
    

    【讨论】:

      【解决方案2】:

      5 转换为(double)

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

      或使用"comparison matcher":

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

      【讨论】:

      • 这将用于比较,但我将 getDiscountPrice 函数中的返回值相乘,因此它将在 getDiscountPrice 函数中失败,而不是在测试中。在 willReturn 中强制转换为 double 也会失败。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-01
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      相关资源
      最近更新 更多