我以前从未编写过测试用例,现在正试图为我编写的API编写测试用例。
我正试图用邮件请求呼叫一条路线,所以我使用了以下方法:
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());
}
这总是失败的错误:
断言404与200 匹配失败
这自然表明它将请求发送到错误的路径。我如何确保它被发布到正确的URL,以及如何查看它试图访问的内容?
我已经尝试将我的.env
文件中的APP url更新为http://localhost/gm-api/public
,也尝试将config/app.php
文件中的url更新为。
我还将库存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);
}
这样做的好处是,您可以使用APP_URL
在.env
文件中设置基本URL,这样做很好。
我不确定为什么在默认测试用例中更改$baseUrl
后,$this->call()
无法工作——我只能假设它仍然命中了错误的URL。然而,使用Guzzle为我解决了这个问题,并且实际上也在测试服务器的配置——假设PHPUnit启动了自己的版本,但这是在测试当前的服务器环境。