I'm trying to write a test class for a shopping cart. Here is what I have:

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类在多个不同的控制器中得到了很好的解决.

Why can't Laravel resolve it during my tests?

I refered to this post as well but still didn't have any luck.

推荐答案

我想出来了.这是更新后的课程.

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

}

Thanks to @edcs for guiding me in the right direction. You need to use a setUp function and not __construct as the app instance hasn't been created yet.

Laravel相关问答推荐

子目录中具有Vue实例的Laravel不起作用

Laravel:通过数据透视表数据限制多对多Eager 加载

1 子编译中的警告(使用'stats.children:true'和'--stats-children'了解更多详细信息)

从 Laravel Session 数组中删除项目

Laravel Blade 模板 @foreach 订单

Carbon(laravel)处理无效日期

找不到列:1054字段列表中的未知列0-Laravel-我的代码中的任何地方都没有0列

Laravel Blade 没有额外的空格?

SQLSTATE [01000]:警告:1265 列的数据被截断(truncated)

使用数据库中的值进行动态邮件配置 [Laravel]

如何更改 Handlebars.js 的默认分隔符?

laravel Blade中多选选项中的旧值

如何在 Laravel 5.1 中为Electron邮件添加标题

Laravel 中的填充方法不起作用?

将自定义消息(或任何其他数据)传递给 Laravel 404.blade.php

如果用户未登录 Laravel,则重定向到登录

在 Laravel 中结合 AND/OR Eloquent的查询

Eloquent的 attach/detach/sync 触发任何事件?

Laravel s3 多桶

如何使用队列设置高、低和中优先级Electron邮件?