我以前从未编写过测试用例,现在正尝试为我编写的 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());
}
这总是失败并出现错误:
Failed asserting that 404 matches 200
这自然表明它正在将请求发送到错误的路径。我如何才能确保它被发布到正确的 URL 以及我如何才能看到它试图达到的目标?
我已经尝试将 .env
文件中的 APP url 更新为 http://localhost/gm-api/public
并在我的 config/app.php
文件也是。
我还更新了库存 TestCase.php
:
protected $baseUrl = 'http://localhost/gm-api/public';
我哪里错了?
最佳答案
我解决了这个问题,个人认为这是一种更好的方法,只需使用 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);
}
这样做的好处是,您只需在 .env
文件中使用 APP_URL
设置基本 URL,就可以了。
我不确定为什么在默认测试用例中更改 $baseUrl
后我无法让 $this->call()
工作 - 我只能假设它仍然访问了错误的 URL。然而,使用 Guzzle 已经为我解决了这个问题,并且实际上也在测试服务器的配置 - 假设 PHPUnit 启动了它自己的版本,但这是在测试当前的服务器环境。
关于PHPUnit 在应该为 200 时返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36591012/