php - Laravel 单元测试依赖注入(inject)

标签 php laravel unit-testing phpunit

我正在尝试为购物车编写测试类。这是我所拥有的:

ShoppingCartTest.php

class ShoppingCartTest extends TestCase {

    use DatabaseTransactions;

    protected $shoppingCart;

    public function __construct() {
        $this->shoppingCart = resolve('App\Classes\Billing\ShoppingCart');
    }

    /** @test */
    public function a_product_can_be_added_to_and_retrieved_from_the_shopping_cart() {

        // just a placeholder at the moment
        $this->assertTrue(true);
    }

}

但是,当我运行 phpunit 时,Laravel 似乎无法解析我的 ShoppingCartClass。

这里是错误:

Fatal error: Uncaught exception 'Illuminate\Contracts\Container\BindingResolutionException'
with message 'Unresolvable dependency resolving
[Parameter #0 [ <required> $app ]] in class Illuminate\Support\Manager'
in C:\Development Server\EasyPHP-Devserver-16.1\eds-www\nrponline\vendor\laravel\framework\src\Illuminate\Container\Container.php:850

我的 ShoppingCart 类在许多不同的 Controller 中解析得很好。

为什么 Laravel 无法在我的测试中解析它?

我引用了 this post也是,但仍然没有任何运气。

最佳答案

我想通了。这是更新后的类(class)。

class ShoppingCartTest extends TestCase {

    use DatabaseTransactions;

    protected $shoppingCart;

    public function setUp() {

        parent::setUp();

        $this->shoppingCart = $this->app->make('App\Classes\Billing\ShoppingCart');
    }

    /** @test */
    public function a_product_can_be_added_to_and_retrieved_from_the_shopping_cart() {

        // just a placeholder at the moment
        $this->assertTrue(true);
    }

}

感谢@edcs引导我朝着正确的方向前进。 您需要使用 setUp 函数而不是 __construct,因为尚未创建 app 实例。

关于php - Laravel 单元测试依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40657440/

相关文章:

php - 为多个站点和每个项目安装使用 vagrant 和 homestead

php - pdo 模块已启用,但我有 "PHP Fatal error: Class ' PDO' 未找到”!

python - Django 数据迁移在运行 manage.py test 时失败,但在运行 manage.py migrate 时失败

java - Mockito:@Mock 对象何时初始化以及它调用哪个构造函数

unit-testing - Grails listOrder中单元测试中的@Mock域对象动态查找器抛出异常

php - 在 where 子句中使用 php 变量时,MySQL 查询不起作用

php - Laravel 以一种很好的方式从 Controller 定义默认布局

php - 无法让发布的变量在表单中回显

php - Codeigniter insert_batch for 循环问题

php - 在数据库中存储学分