PHPUnit 在应该为 200 时返回 404

标签 php laravel phpunit 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());
    }

这总是失败并出现错误:

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/

相关文章:

php - CakePHP 中多个表的公共(public)列

php - GIT 中的 Composer 和 composer.lock 并 merge 冲突

php - 使用docker-compose中的docker远程解释器在Intellij中运行PHPUnit期望 “/opt/project”中的项目

PHPUnit:如何使用类实例化来测试方法?

android - 无法使用 Retrofit 2 上传图像

laravel - PHPUNIT 测试 - 预期状态 200 但收到 500

PHP 比较运算符和数据类型

php - 在 1 个下拉条目中显示 2 个数组值

php - 在 zend 中在哪里保存自定义自动加载器?

php - Laravel:如何在 maatwebsite DOMPDF 导出中更改 PDF 样式?