【问题标题】:Authorized user's id is empty during unit testing单元测试期间授权用户的 id 为空
【发布时间】:2014-08-03 19:05:31
【问题描述】:

我在 Laravel 4 中遇到了这个问题:

控制器中的一个简单方法:

public function getHello()
{
    if( !\Auth::check() ){
        return Redirect::route('user.login');
    }

    //this is working fine just in the web, not for phpunit in the console
    echo \Auth::id();
    //this is working for both
    echo \Auth::user()->id;
}

还有一个简单的测试用例:

public function testHello()
{
    $user = User::find(1);
    $this->be($user);
    $this->action('GET', 'HomeController@getHello');
}

我只是不明白为什么“Auth::id()”在测试期间返回空/空字符串。

【问题讨论】:

  • 您是否在数据库中植入了用户?
  • @philipbrown 是的,第二个 (\Auth::user()->id) 工作正常。
  • 我的意思是,您在测试期间为您的数据库播种了吗?
  • @philipbrown 为什么在测试期间再次播种?我已经调整了所有环境的配置以使用相同的数据库,所以因为 auth::user->id 返回正确的值,它表明数据库连接和播种没有问题。对吗?

标签: php unit-testing laravel laravel-4 phpunit


【解决方案1】:

我不确定$this->be() 到底做了什么,但我假设它会创建一个Session 并以$user 的身份登录。

如果不是,那就是问题所在。会话是在 Web 请求期间自动创建的,而不是在单元测试期间。

然而,这个测试实际上并没有测试任何东西。您可能需要进行一些重构以揭示实际发生的情况。

public function testHello()
{
    Session::start();
    $user = User::find(1);
    Auth::login($user);
    $response = $this->action('GET', 'HomeController@getHello');
    $this->assertEquals($user->id, $response->getContent());
}

【讨论】:

    猜你喜欢
    • 2018-02-16
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多