在使用 PHPSpec 进行测试时,如何使用注入(inject)到我的方法中的类接口(interface)而不是实际的具体类?
例如,我有一个 Product
类,它将 VariationInterface
注入(inject)到一个方法中:
/**
* ...
*/
public function addVarient(VarientInterface $varient)
{
return $this->varients->add($varient);
}
尽管由于 PHPSpec 没有 IOC 容器来将 VarientInterface
绑定(bind)到 Varient
,但我无法真正测试我的类。
针对接口(interface)而非具体类编写代码不是最佳实践吗?
最佳答案
您可以在 PHPSpec 中模拟具体类和接口(interface)。
请验证这个例子:
<?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 模拟)。
请查看关于模拟的官方 phpspec 文档 http://www.phpspec.net/docs/introduction.html#prophet-objects
关于php - 使用PHPSpec时如何使用类接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490259/