【问题标题】:Laravel PHPUnit unable to test GET parametersLaravel PHPUnit 无法测试 GET 参数
【发布时间】:2021-12-04 18:57:57
【问题描述】:

我有一个 Laravel 8 应用程序,我正在开发我需要使用 GET 参数的地方(例如 test?num=1),但不幸的是,我似乎无法弄清楚如何针对此运行单元测试.

我遵循了我可以在网上找到的指导(包括 Laravel phpunit testing get with parameters,它看起来很有希望)但是,这些方法似乎都不起作用。

为了尝试找出问题所在,我创建了一个非常简单的版本,并且得到了相同的行为。如果我直接访问 URL,它会按预期工作,但单元测试会失败。

routes\web.php

Route::get('/test', 'TimeController@test')->name('myTest');

app\Http\Controllers\TimeController.php

public function test()
{
    return $_GET['num'] ?? "Num not provided";
}

test\Unit\Http\Controllers\TimeControllerTest.php

/** @test */
public function num_test_1()
{
    $params = ["num" => "1"];
    $response = $this->get('/test?num=1');
    $response->assertSeeText("1");
}
/** @test */
public function num_test_2()
{
    $params = ["num" => "1"];
    $response = $this->get('/test', $params);
    $response->assertSeeText("1");
}
/** @test */
public function num_test_3()
{
    $params = ["num" => "1"];
    $response = $this->call('GET', '/test', $params);
    $response->assertSeeText("1");
}

上述所有三个测试都失败并显示消息

断言 'Num not provided' 包含“1”失败。

我什至不遗余力地删除了node_modules 和vendor 文件夹,以防万一我有损坏的PHPUnit 包或其他东西。

我错过了什么明显的东西吗?这感觉像是一件应该很容易做到的事情,而且很多人以前都会这样做。

【问题讨论】:

    标签: php laravel unit-testing phpunit


    【解决方案1】:

    它工作正常。

    你应该像这样改变你的方法:

    public function test(Request $request)
    {
        return $request->input('num') ?? "Num not provided";
    }
    

    或者用query方法:

    public function test(Request $request)
    {
        return $request->query('num') ?? "Num not provided";
    }
    

    如果没有找到,你也可以传递你想要的默认值,而不是使用??:

    public function test(Request $request)
    {
        return $request->input('num', 'Num not provided');
    }
    
    public function test(Request $request)
    {
        return $request->query('num', 'Num not provided');
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-08
      • 2019-03-06
      • 2013-04-14
      • 2014-09-21
      • 2017-07-27
      • 1970-01-01
      • 2015-07-21
      • 2017-11-29
      • 2021-08-20
      相关资源
      最近更新 更多