【问题标题】:How to mock $_SERVER variables for laravel tests?如何为 laravel 测试模拟 $_SERVER 变量?
【发布时间】:2017-11-22 06:55:37
【问题描述】:

我正在使用 shibboleth apache 模块进行联合单点登录。它使用来自活动目录的用户权利设置$_SERVER 变量。在我的 laravel 应用程序中,我使用了一个自定义身份验证和用户提供程序,它利用这些权利进行资源授权。

我的简化用户模型是这样的:

public function isAdmin()
{
    return Request::server('entitlement') === 'admin';
}

但是,我不知道如何测试它,因为 Request::server 始终没有返回该值。

public function setUp()
{
    $_SERVER['entitlement'] = 'admin';
    parent::setUp();
}

public function test_admin_something()
{
    $user = factory(User::class)->create();

    $response = $this
        ->actingAs($user)
        ->get('/admin/somewhere');

    var_dump($_SERVER['entitlement']);        // string(5) "admin"
    var_dump(Request::server('entitlement')); // NULL

    $response->assertStatus(200); // always fails 403
}

我还尝试了setUpBeforeClass 并检查了所有其他在测试期间似乎被忽略的服务器变量,以代替定制的请求对象。我也无法模拟请求外观,per the documentation。

【问题讨论】:

  • 尝试将->get('/admin/somewhere') 更改为->call('GET', '/admin/somewhere', ['entitlement' => 'admin']);。见:laravel.com/docs/5.2/testing#custom-http-requests
  • 你用的是什么测试套件,什么版本。
  • @Ohgodwhy phpunit 5.7.20 laravel 5.4.24
  • @btl 谢谢,但没有骰子,这是为了传递输入数据填充 $_GET 和 $_POST 但不是 $_SERVER

标签: php laravel unit-testing phpunit


【解决方案1】:

深入了解the source code 揭示了一个未记录的方法withServerVariables

public function test_admin_something()
{
    $user = factory(User::class)->create();

    $response = $this
        ->withServerVariables(['entitlement' => 'admin'])
        ->actingAs($user)
        ->get('/admin/somewhere');

    $response->assertStatus(200);
}

【讨论】:

    猜你喜欢
    • 2017-08-24
    • 1970-01-01
    • 2020-09-16
    • 2022-01-27
    • 2022-08-11
    • 2016-06-11
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多