php - 使用PHPSpec时如何使用类接口(interface)

标签 php testing laravel bdd phpspec

在使用 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/

相关文章:

php - 在 Nova Action fields() 上运行 where()->get()

php - sendmail Laravel 不发送电子邮件

php - 行为驱动开发和 PHP 应用程序

php - 1 个具有关系的多个数据库的表单

php - 使用 php 从 mysql 填充下拉框

ruby-on-rails - Rspec 正在将属性视为方法

testing - 为什么边界是错误的常见位置?

ruby-on-rails - Rails 中 around_action 设置的测试条件

php - 使用 Laravel Eloquent 和命名绑定(bind)的 SQL 查询 : mixed named and positional parameters

Laravel 5 表单请求,创建时需要输入,但编辑时可选