Laravel 模拟门面 shouldReceive 未按预期工作

Laravel Mock Facade shouldReceive Not Working As Intended

此测试失败,因为它永远不会通过 Auth::attempt() 函数调用。我放了一个 dd() 声明来证明它不会成功。

如果我删除两个 Auth::shouldReceive() 代码将 运行 第一个 dd() 语句。

如果我只保留一个 Auth::shouldReceive(),第一个 dd() 语句将永远不会被调用。

如果我添加 ->twice() 而不是 ->once() 则不会抛出任何错误,这很奇怪,因为它应该抱怨它只被调用了一次。

如果我在控制器的第一行放置一个 dd() 语句,它不会 运行 直到我删除 Auth::shouldReceive() 函数。

我一定是傻了,因为我看了很多教程所以我没有得到。

控制器

public function postLogin() {
    $email = Input::get('email');
    $password = Input::get('password');
    dd('Does not make it to this line with auth::shouldReceive() in the test');
    if (Auth::attempt(array('email'=>$email, 'password'=>$password))) {
        dd("Doesn't make it here either with auth::shouldReceive() mock.");
        $user = Auth::user();
        Session::put('user_timezone', $user->user_timezone);
        return Redirect::to('user/dashboard')->with('message', 'You are now logged in!');
    } else {
        return Redirect::to('user/login')->with('message', 'Your username/password combination was incorrect')->withInput();
    }
}

测试

public function testUserTimezoneSessionVariableIsSetAfterLogin()
{
    $user = new User();
    $user->user_timezone = 'America/New_York';
    $user->email = 'test@test.com';
    $user->password = 'test';

    $formData = [
        'email' => 'test@test.com',
        'password' => '123',
    ];

    \Auth::shouldReceive('attempt')->once()->with($formData)->andReturn(true);
    \Auth::shouldReceive('user')->once()->andReturn($user);

    $response = $this->call('POST', '/user/login', $formData);
    $this->assertResponseStatus($response->getStatusCode());


    $this->assertSessionHas('user_timezone');
}

问题是我的 UserController 的构造函数中有 parent::construct()。显然这会导致模拟出现问题。

我认为这是 parent::construct() 所必需的,因为我在 UserController 中有一个自定义构造函数。