【问题标题】:Mockery mock method inside closure闭包内的嘲弄模拟方法
【发布时间】:2015-07-17 16:34:21
【问题描述】:

call_user_func() 示例调用的闭包内的单元测试方法有问题:

public function trans($lang, $callback)
{
   $this->sitepress->switch_lang($lang);
   call_user_func($callback);
}

在控制器上:

public function sendMail()
{
   $foo = $baz = 'something';
   $mail = $this->mailer;
   $this->helper->trans_c('en', function() use($foo, $baz, $mail) {
      $mail->send('Subject', $foo, $baz);
   });
}

测试用例:

public function testSomething()
{
   $helperMock = Mockery::mock('Acme\Helper');
   $helperMock->shouldReceive('trans_c')->once(); // passed

   $mailMock = Mockery::mock('Acme\Mail');
   $mailMock->shouldReceive('send')->once(); // got should be called 1 times instead 0

   $act = new SendMailController($helperMock, $mailMock);
   $act->sendMail();
}

我怎样才能确保->send()方法在闭包trans_c()中被调用

我试过了

$helperMock->shouldReceive('trans_c')->with('en', function() use($mailMock) {
   $mailMock->shouldReceive('send');
});

运气不好。 :(

trans_c 的第二个参数中传递Mockery::type('Closure') 可以正常工作,但我确实需要确保调用邮件类中的send 方法。

【问题讨论】:

  • 请发布您遇到的错误。没有运气对我们没有帮助。

标签: unit-testing laravel-4 mocking phpunit mockery


【解决方案1】:

默认情况下,模拟类不执行真实代码。如果您模拟帮助程序,它将检查是否正在进行调用,但不会执行匿名函数。

通过 mockery,你可以配置期望,以便执行真正的方法:passthru();

试试这个:

$helperMock = Mockery::mock('Acme\Helper');
$helperMock
     ->shouldReceive('trans_c')
     ->once()
     ->passthru()
;

the docs 对此进行了解释。

编辑

也许你真的不需要模拟助手。如果你模拟 Mail 类并期望 send 方法被调用一次,就让真正的助手来做吧。

【讨论】:

    猜你喜欢
    • 2019-06-26
    • 2018-04-05
    • 2017-09-01
    • 2017-12-27
    • 2016-07-12
    • 2016-12-26
    • 2015-12-18
    • 2014-01-29
    • 2015-11-13
    相关资源
    最近更新 更多