[英]PHPUnit is returning 404 when it should be 200
我之前從未編寫過測試用例,並且正在嘗試為我編寫的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網址更新為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);
}
這樣做的好處是,您只需使用APP_URL
在.env
文件中設置基本URL,就可以了。
我不確定為什么在默認測試用例中更改$baseUrl
之后我無法使$this->call()
工作 - 我只能假設它仍然遇到了錯誤的URL。 但是,使用Guzzle已經為我解決了這個問題,並且實際上也測試了服務器的配置 - 假設PHPUnit旋轉了自己的版本,但這是在測試當前的服務器環境。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.