Jam*_*mes 5 php phpunit laravel laravel-5.2
我以前从未编写过测试用例,并且正在尝试为我编写的 API 执行此操作。
我正在尝试使用 post 请求调用路由,因此我使用以下内容:
public function testRequestCorrectApiKey()
{
//Request with X-Authorization sending correct API Key
$response = $this->call('POST', '/authenticate', ['email' => 'testingphpunit@phpunittest.com', 'password' => 'phpunittest', [], [], ['X-Authorization' => '123workingapikey123']]);
$this->assertEquals(200, $response->status());
}
Run Code Online (Sandbox Code Playgroud)
这总是因错误而失败:
断言 404 匹配 200 失败
这自然表明它正在将请求发送到错误的路径。如何确保将其发布到正确的 URL 以及如何查看它试图访问的内容?
我已经尝试将我的.env文件中的 APP url 更新到http://localhost/gm-api/public我的config/app.php文件中。
我还更新了库存TestCase.php:
protected $baseUrl = 'http://localhost/gm-api/public';
Run Code Online (Sandbox Code Playgroud)
我哪里错了?
我解决了这个问题,个人认为这是一种更好的方法,只需使用 Guzzle 来运行测试即可。
/**
* Send a request with the correct API Key
*/
public function testRequestCorrectApiKey()
{
$key = ApiKey::find(1);
//Request with X-Authorization sending correct API Key
$path = 'authenticate';
$client = new Client(['base_uri' => env('APP_URL', 'http://localhost/gm-api/public/')]);
$response = $client->request("POST", $path, ["email" => "testingphpunit@phpunittest.com", "password" => "phpunittest", "headers" => ["X-Authorization" => $key->key ]]);
$status_code = $response->getStatusCode();
$this->assertEquals(200, $status_code);
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是,您只需在.env文件中设置基本 URL APP_URL,就可以了。
$this->call()我不确定为什么在更改$baseUrl默认测试用例后我无法开始工作 - 我只能假设它仍然访问了错误的 URL。然而,使用 Guzzle 已经为我解决了这个问题,并且实际上也在测试服务器的配置 - 鉴于 PHPUnit 启动了自己的版本,但这正在测试当前的服务器环境。