PHPUnit 在应该为 200 时返回 404

PHPUnit is returning 404 when it should be 200

我以前从未编写过测试用例,但我正在尝试为我编写的 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

这自然表明它正在将请求发送到错误的路径。我怎样才能确保它被 post 编辑到正确的 URL 以及我怎样才能看到它试图达到的目标?

我已经尝试将我的 .env 文件中的应用程序 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);
}

这样做的好处是,您只需使用 APP_URL.env 文件中设置基础 URL 就可以了。

我不确定为什么我在更改默认测试用例中的 $baseUrl 后无法让 $this->call() 工作 - 我只能假设它仍然是错误的 URL.但是,使用 Guzzle 已经为我解决了这个问题,并且实际上也在测试服务器的配置——假设 PHPUnit 启动了它自己的版本,但这是在测试当前的服务器环境。