Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit call to undefined method `Mock_x_::method()`

I'm trying to create my first phpunit test and find myself needing to stub a method on an IMailer interface.

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

However, I keep getting

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

a var_dump($mailer); results in

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

Working with the expect($this->any()) gives a dito error - it seems that the mocked object does not have any mock functionality...

I'm running phpunit 3.7.28, and php 5.5.9, on an ubuntu box.

How come? How can I fix it?

like image 950
xtofl Avatar asked Jun 16 '15 05:06

xtofl


1 Answers

The getMockBuilder function accepts only the className as parameter. The correct way to initialize your mock object methods would be to use setMethods function (see phpunit docs)

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

Additionally you probably want to have some expects definition also when you use your mock object:

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

EDIT

The above holds true for newer phpunit versions. For phpunit 3.7.28 the mock object usage is a bit different (i.e. the expects seems to be mandatory and willReturn is not yet available). For 3.7.28 version you should modify the second part to:

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

I would recommend updating to later phpunit version as it seems to be somewhat difficult to find documentation to this much older releases.

like image 121
ejuhjav Avatar answered Oct 01 '22 00:10

ejuhjav