dregduc63699 2015-06-26 04:15
浏览 72
已采纳

Laravel Mock Facade应该不会像预期的那样工作

This test fails because it will never pass the Auth::attempt() function call. I put a dd() statement to prove that it won't make it.

If I remove the two Auth::shouldReceive() the code will run the first dd() statement.

If I keep even one Auth::shouldReceive() the first dd() statement will never get called.

If I add ->twice() instead of ->once() there are no errors thrown which is odd because it should complain that it has only been called once.

If I place a dd() statement at the first line of the controller it does not run until I remove the Auth::shouldReceive() functions.

I must be something silly that I'm not getting because I've looked over many tutorials.

Controller

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();
    }
}

Test

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');
}
  • 写回答

1条回答 默认 最新

  • dsqpx86002 2015-06-28 00:08
    关注

    The problem was that I had parent::construct() in the constructor of my UserController. Apparently this causes issues with mocks.

    I assumed this was necessary to have parent::construct() because I had a custom constructor in UserController.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题