1

我有一个带有 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 调用之前以某种方式设置依赖项吗?

4

1 回答 1

3

您可以使用以下方法在来自路由的请求之间取消设置控制器实例:

$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;
}
于 2019-01-25T09:15:46.990 回答