该测试失败,因为它永远不会通过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中有一个自定义构造函数。

关于php - Laravel模拟立面应该不会按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31064804/

10-16 11:26