giggsey
giggsey

Reputation: 933

PHPUnit Mock seemingly not calling public function

Code:

MyMockClass.php

<?php
class MyMockClass
{
    public function __construct($l)
    {
        // Do nothing with it
    }

    protected function loadData($var)
    {
        // Do something, it doesn't matter what
        return null;
    }

    public function onEvent($key)
    {
        return $this->loadData($key);
    }
}

MockTest.php

<?php
class MockTest extends \PHPUnit_Framework_TestCase
{
    public function testPHPUnitMock()
    {
        $mock = $this->getMockBuilder('MyMockClass')->setConstructorArgs(array(true))->getMock();
        $mock->expects($this->once())->method('loadData')->with('TEST')->will($this >returnValue(true));

        $this->assertEquals(true, $mock->onEvent('TEST'));
    }

}

When I run this test, it fails, with the following output:

PHPUnit_Framework_ExpectationFailedException : Failed asserting that null matches expected true.
Expected :true
Actual   :null

I'm trying to execute onEvent, which in turn executes a function I have mocked, and changed the outcome of. But the onEvent function doesn't seem to get called. If I put mail() (or something similar) in onEvent, I don't receive any mail.

Upvotes: 2

Views: 2763

Answers (1)

Cyprian
Cyprian

Reputation: 11374

If you don't tell the mock builder which methods you are going to mock - all methods from the mocked class will be mocked by default. 

In your case when you invoke onEvent method in your test, actually you've invoked a mocked method.

If you specify method you want to mock, then the mock builder will mock only these method and leave the rest as they are in original class.

So, try build your mock in that way:

public function testPHPUnitMock()
{
    $mock = $this->getMockBuilder('MyMockClass')
        ->setMethods(array('loadData')) // this line tells mock builder which methods should be mocked
        ->setConstructorArgs(array(true))
        ->getMock();
    $mock->expects($this->once())->method('loadData')->with('TEST')->will($this->returnValue(true));

    $this->assertTrue($mock->onEvent('TEST'));
}

Upvotes: 7

Related Questions