PHPUnit 调用未定义的方法 `Mock_x_::method()`

标签 php mocking phpunit undefined

我正在尝试创建我的第一个 phpunit 测试,发现自己需要在 IMailer 接口(interface)上 stub 一个方法。

interface IMailer
{
    public function send($to, $from, $cc, $subject, $body);
    public function sent();
}

    $mailer = $this->getMockBuilder(
        'IMailer',
        array('send', 'sent'))->getMock();

    $mailer->method('send')->willRreturn(0);

然而,我不断得到

PHP Fatal error: 
  Call to undefined method Mock_Mailer_13fc0a04::method()
  in ...Test.php on line 16

var_dump($mailer); 结果

class Mock_IMailer_4c3e02a7#215 (1) {
  private $__phpunit_invocationMocker =>
  NULL
}

使用 expect($this->any()) 会给出一个 dito 错误 - 模拟对象似乎没有任何模拟功能......

我在 ubuntu 机器上运行 phpunit 3.7.28 和 php 5.5.9。

怎么会?我该如何解决?

最佳答案

getMockBuilder 函数只接受类名作为参数。初始化模拟对象方法的正确方法是使用 setMethods 函数(参见 phpunit docs)

   $mailer = $this->getMockBuilder('IMailer')
       ->setMethods(array('send', 'sent'))
       ->getMock();

此外,当您使用模拟对象时,您可能还希望有一些期望定义:

   $mailer->expects($this->any())
        ->method('send')
        ->willReturn(0);

编辑

以上内容适用于较新的 phpunit 版本。对于 phpunit 3.7.28,模拟对象的使用有点不同(即 expects 似乎是强制性的,willReturn 尚不可用)。对于 3.7.28 版本,您应该将第二部分修改为:

   $mailer->expects($this->any())
        ->method('send')
        ->will($this->returnValue(0));

我建议更新到更高的 phpunit 版本,因为要找到这么旧版本的文档似乎有点困难。

关于PHPUnit 调用未定义的方法 `Mock_x_::method()`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30859207/

相关文章:

php - 模拟 Laravel 的 Request::segment 方法

php - 重写 CI url

caching - Redis 缓存驱动程序在 PHPUnit 中抛出异常

php - Laravel:如何将查询或阻止查询的尝试时间限制在 30 秒内?

java - 使用 Mockito 测试重复代码

PHPUnit:模拟除某些方法之外的所有方法

java - 我可以使用注释将原始变量注入(inject)模拟类吗?

php - 如何对使用 ORM 的应用程序进行单元测试?

php - 将 SQL 查询的数据返回到数组中

php - Tinymce 使用 php 获取内容