【发布时间】:2020-06-15 06:23:03
【问题描述】:
使用 Laravel Framework 5.8.36,我正在尝试运行一个调用控制器的测试,其中 __construct 方法使用 DI,如下所示:
class SomeController extends Controller {
public function __construct(XYZRepository $xyz_repository)
{
$this->xyz_repository = $xyz_repository;
}
public function doThisOtherThing(Request $request, $id)
{
try {
return response()->json($this->xyz_repository->doTheRepoThing($id), 200);
} catch (Exception $exception) {
return response($exception->getMessage(), 500);
}
}
}
如果我通过浏览器运行代码或像邮递员中的 api 调用一样调用它,这工作正常,但是当我从测试中调用 doThisOtherThing 方法时,我收到以下错误:
ArgumentCountError:函数 App\Http\Controllers\SomeController::__construct() 的参数太少,在第 28 行的 /var/www/tests/Unit/Controllers/SomeControllerTest.php 中传递了 0,而预期正好是 1
这告诉我,当我运行测试时,DI 出于某种原因无法正常工作。有任何想法吗?这是我的测试:
public function testXYZShouldDoTheThing()
{
$some_controller = new SomeController();
$some_controller->doThisOtherThing(...args...);
...asserts...
}
我已经尝试过在 setUp 方法中使用 app 上的 bind 和 make 方法,但没有成功:
public function setUp(): void
{
parent::setUp();
$this->app->make('App\Repositories\XYZRepository');
}
【问题讨论】:
标签: laravel dependency-injection phpunit