1

使用 PHPSpec 进行测试时,如何使用注入到我的方法中的类接口而不是实际的具体类?

例如,我有一个Product将 aVariationInterface注入方法的类:

/**
 * ...
 */
public function addVarient(VarientInterface $varient)
{
    return $this->varients->add($varient);
}

尽管由于 PHPSpec 没有要绑定VarientInterface的IOC 容器,Varient但我无法真正测试我的类。

编写接口而不是具体类不是最佳实践吗?

4

1 回答 1

1

您可以在 PHPSpec 中模拟具体的类和接口。

请验证此示例:

<?php

//file spec/YourNameSpace/ProductSpec.php

namespace spec\YourNameSpace\Product;

use YourNameSpace\VarientInterface;
use PhpSpec\ObjectBehavior;

class ProductSpec extends ObjectBehavior
{
    function it_is_varients_container(VarientInterface $varient)
    {
        $this->addVarient($varient);

        $this->getVarients()->shouldBe([$varient]);
    }
}

您只需将 VarientInterface 作为参数传递给测试方法。这个 VarientInterface 在下面被 PhpSpec 模拟(实际上是 Prophecy)。

请查看有关模拟http://www.phpspec.net/docs/introduction.html#prophet-objects的官方 phpspec 文档

于 2014-12-16T17:28:30.367 回答