我正在尝试为购物车编写测试类。这是我所拥有的:
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/