Cam*_*ilo 4 php phpunit dependency-injection laravel
我正在尝试向类添加自定义断言,TestReponse以便我可以做这样的事情:
$response = $this->json('POST', '/foo/bar');
$response->myCustomAssertion();
Run Code Online (Sandbox Code Playgroud)
我尝试创建一个App\TestResponse扩展原始类的类,然后将其绑定到App\Provider\AppServiceProvider类中。
public function register()
{
$this->app->bind('Illuminate\Foundation\Testing\TestResponse', function ($app) {
return new App\TestResponse();
});
}
Run Code Online (Sandbox Code Playgroud)
但$response->json()仍然返回原来的一个而不是我自己的实现。
如何扩展TestResponse课程?
Jam*_*low 13
如果你想要更细粒度的控制,你也可以Illuminate\Foundation\Testing\TestResponse像你所做的那样扩展,然后覆盖类中的createTestResponse方法TestCase以返回自定义响应类的实例:
// Laravel 8 and above
protected function createTestResponse($response)
{
return tap(App\TestResponse::fromBaseResponse($response), function ($response) {
$response->withExceptions(
$this->app->bound(LoggedExceptionCollection::class)
? $this->app->make(LoggedExceptionCollection::class)
: new LoggedExceptionCollection
);
});
}
// Before Laravel 8
protected function createTestResponse($response)
{
return App\TestResponse::fromBaseResponse($response);
}
Run Code Online (Sandbox Code Playgroud)
从Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.
lag*_*box 10
该类TestResponse使用该Macroable特征,因此您可以在运行时添加宏函数。
TestResponse::macro('nameOfFunction', function (...) {
...
});
Run Code Online (Sandbox Code Playgroud)
您可以将其添加到服务提供者的boot方法中或在需要调用该宏方法之前的某个位置。