分享 Laravel 测试小技巧
您好,这里有一些使用 Laravel 进行测试的技巧,这篇文章将持续更新。
获请求以API形式的JSON格式验证错误
使用测试案例方法 "json()"
$this->json('post', '/api/any', ['key' => 'value']);
如果要发出ajax或fetch请求,则默认情况下错误将显示为json,要测试此验证错误,只需使用 json()
方法。
创建请求类
如果您使用依赖项注入,这将特别有用。
- 创建请求类并添加参数
$request = new \Illuminate\Http\Request();
$request->replace([
"name" => "John Doe",
"email" => "john@doe.com",
]);
- 它也适用于表单请求类:
$request = new FormRequestCustomClass();
$request->replace([
"name" => "John Doe",
"email" => "john@doe.com",
]);
轻松阅读 JSON 响应内容。
您可以将 json()
方法与 getContent()
方法链接在一起,以允许您查看响应内容,通常,约定是将响应保存在变量中以进行断言,在这种情况下,您希望查看响应 以JSON格式,您可以使用 json_encode()
php本机函数来获得更好的可读性:
$response = $this->json('get', '/api/anyendpoint');
dd(json_decode($response->getContent()));
它适用于其他方法发出请求,例如 get
, post
,put
,delete
,但在 json
方法中更有意义,因为它返回一个 JSON。
重定向测试
通常,在您的控制器中,您可以通过不同的方式返回重定向响应:
return redirect('/users'); // case 1 not the best approach
return redirect->to('/users'); // case 2 still not the best
return redirect()->route('users); // case 3 a good practice
return redirect()->back(); // case 4 if your previous endpoint was "/users" this is fine
好吧,要在多种情况下测试重定向,您可以执行以下操作:
$response->assertRedirect('/users'); // this works for case 1, 2, 3
$response->assertRedirect(route('users')); // this works for case 1, 2, 3
如您所见,唯一无法轻松测试的方法是使用助手 back()
的方法,Laravel 可以测试 redirect
方法(如果这添加了显式路由),因此这4种情况只有通过测试才能起作用 重定向状态,例如:
$response->assertStatus(302);
$response->assertRedirect();
这可能不是粒度测试,因为我们仅测试正在执行重定向,但是当您需要使用在某些情况下特别有用的 back()
帮助程序时,此方法适用。
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。