brainmonger
brainmonger

Reputation: 687

PHPUnit - Trying to call a method from an object passed in as a parameter

I'm trying to test calling a method of a request object which was passed into my function as a parameter, but I keep getting an error. Any idea what I could be doing wrong? Here's what I have:

In my action helper

public function direct($request)
{
    $myData = $request->getPost('myData');
}

In my test file

public function testDirect()
{
    $subject = $this->getMockBuilder('Default_Controller_Action_Helper_MyFile')
        ->disableOriginalConstructor()
        ->setMethods(
            array(
                'direct'
            )
        )
        ->getMock();

    $myData = 'myData';

    $request = $this->getMockBuilder('Zend_Controller_Request_Http')
        ->disableOriginalConstructor()
        ->setMethods(array('getPost'))
        ->getMock();

    $request->expects($this->exactly(1))
        ->method('getPost')
        ->with('myData')
        ->will($this->returnValue($myData));

    $subject->direct($request);
}

I get the following error:

There was 1 failure:

1) Default_Controller_Action_Helper_MyFile::testDirect
Expectation failed for method name is equal to <string:getPost> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

Upvotes: 0

Views: 51

Answers (1)

Kuba Birecki
Kuba Birecki

Reputation: 3016

You should pass null to setMethods() in $subject definition to prevent mocking the methods from your class.

It's not enough to drop the setMethods call as the mock builder mocks all methods by default.

This should work:

public function testDirect()
{
    $subject = $this->getMockBuilder('Default_Controller_Action_Helper_MyFile')
        ->disableOriginalConstructor()
        ->setMethods(null)
        ->getMock();

    $myData = 'myData';

    $request = $this->getMockBuilder('Zend_Controller_Request_Http')
        ->disableOriginalConstructor()
        ->setMethods(array('getPost'))
        ->getMock();

    $request->expects($this->exactly(1))
        ->method('getPost')
        ->with('myData')
        ->will($this->returnValue($myData));

    $subject->direct($request);
}

Upvotes: 1

Related Questions