【问题标题】:How to mock authentication user on unit tests with Codeception in Laravel 5?如何在 Laravel 5 中使用 Codeception 在单元测试中模拟身份验证用户?
【发布时间】:2019-03-27 04:48:15
【问题描述】:

我必须将我的单元测试转换为代码接收。我需要使用本文中的 loginWithFakeUser() 函数 - How to mock authentication user on unit test in Laravel?

public function loginWithFakeUser() {
    $user = new User([
        'id' => 1,
        'name' => 'yish'
    ]);
    $this->be($user);
}

当我的课程已经在扩展\Codeception\Test\Unit 时,我如何使用$this->be()?我不知道我应该use .. 或如何正确使用。将函数 loginWithFakeUser() 放在这个里面:

use Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication;
use Illuminate\Foundation\Testing\Concerns\InteractsWithSession;

class AdminTest extends \Codeception\Test\Unit {
    use InteractsWithAuthentication;
    use InteractsWithSession;
}

给我一​​个错误:

[ErrorException] 未定义属性:AdminTest::$app

我不确定如何设置 $app 变量。请帮我。非常感谢!

【问题讨论】:

    标签: laravel unit-testing codeception laravel-authentication


    【解决方案1】:

    我可以通过模拟 Auth 类来解决这个问题。

    $oUser = new User([
        'id' => 1,
        'name' => 'yish'
    ]);
    
    Auth::shouldReceive('check')->once()->andReturn(true);
    Auth::shouldReceive('user')->once()->andReturn($oUser);
    

    在我的实际代码中它用作:

    if(Auth::check() === true) {
        $sName = Auth::user()->name;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      相关资源
      最近更新 更多