我有一个带有DI的Laravel控制器
__construct(Model1 $m1, Model2 $m2, $SomeService $s) {
$this->m1 = $m1;
$this->m2 = $m2;
$this->s = $s;
}
我有一个基于此控制器的带有调用或端点的API测试。我正在用不同的有效负载执行8个相同的API URL调用。似乎z控制器构造函数过程需要1次,之后才能与构造的依赖项一起工作。
$response1 = $this->actingAs($admin,'api')->json('POST', '/api/someURL', $payload1);
$response2 = $this->actingAs($admin,'api')->json('POST', '/api/someURL', $payload2);
$responseN = $this->actingAs($admin,'api')->json('POST', '/api/someURL', $payloadN);
我可以在测试中的每个API调用之前以某种方式设置依赖项吗?
答案 0 :(得分:2)
您可以使用以下方法取消路由请求之间的控制器实例设置:
$response1 = $this->actingAs($admin,'api')->json('POST', '/api/someURL', $payload1);
// unset the controller
$this->app->get(Illuminate\Routing\Route::class)->controller = null;
$response2 = $this->actingAs($admin,'api')->json('POST', '/api/someURL', $payload2);
// unset the controller
$this->app->get(Illuminate\Routing\Route::class)->controller = null;
$responseN = $this->actingAs($admin,'api')->json('POST', '/api/someURL', $payloadN);
为什么?
在Illuminate\Routing\Router中,Laravel将当前路由绑定到容器:
protected function findRoute($request)
{
$this->current = $route = $this->routes->match($request);
$this->container->instance(Route::class, $route);
return $route;
}
,并且当在Illuminate\Routing\Route中运行路径控制器时,该控制器实例存储在Route对象中:
public function getController()
{
if (! $this->controller) {
$class = $this->parseControllerCallback()[0];
$this->controller = $this->container->make(ltrim($class, '\\'));
}
return $this->controller;
}