【问题标题】:Laravel Mock Facade shouldReceive Not Working As IntendedLaravel Mock Facade shouldReceive Not Working As Intented
【发布时间】:2015-09-12 21:55:08
【问题描述】:

此测试失败,因为它永远不会通过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');
}

【问题讨论】:

  • 这条路由有中间件吗?
  • 我不知道。就像普通 Laravel 应用程序在 Kernel.php 文件中启用的一样。
  • 只是一个想法,但Auth::user() 可能会被某些内部人员调用。将once()更改为zeroOrMoreTimes(),看看问题是否仍然存在。
  • 完全不调用控制器中的代码之前的结果相同。我尝试在顶部使用 dd() 语句,但它没有执行。
  • 也许这个问题有帮助:stackoverflow.com/a/24033017/919933

标签: php laravel testing phpunit mockery


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 2014-12-04
    相关资源
    最近更新 更多