3
votes

how do I get the real return value of a mocked class/method? I found many possibilities to return fixed values, but I want the result of the mocked method i call


    namespace Updater\Model;

    class TestClass
    {
        public function testFunction(){
            return 12345;
        }
    }


    class DatabaseTest extends PHPUnit_Framework_TestCase
    {

         public function testMock(){
              $mock = $this->getMock('Updater\Model\TestClass', array('testFunction'));
              $mock->expects($this->once())->method('testFunction')

              // Call the Funciton.... here i would like to get the value 12345 
              $result = $mock->testFunction();
         }
    }

I didn't find anything how to get the real return value.... frustrating :)

2
You mock the method to get a test result that does not change, so you can test your behavior of the code using the different return values. If you simply want to work with what the method returns, call the method, not the mock.Steven Scott

2 Answers

2
votes

AFAIK you can't do that with PHPUnit native mocks. There is a mocking library called Mockery that can do that:

http://docs.mockery.io/en/latest/reference/expectations.html

look for the passthru() method.

That said, it's not very usual that you need to call the real method from a mock. Can you explain a real case? You mock methods so you can take control over their behaviour (return value, throwing an Exception, etc).

2
votes

You can do it in PHPunit. Here my example. Take a look at the getMock method where you must specify which method do you want to mock.

<?php


namespace Acme\DemoBundle\Tests;

class TestClass
{
    public function testFunction(){
        return 12345;
    }

    public function iWantToMockThis()
    {
        return 'mockME!';
    }
}

class DatabaseTest extends \PHPUnit_Framework_TestCase
{

    public function testMock(){
        $mock = $this->getMock('Acme\DemoBundle\Tests\TestClass', array('iWantToMockThis'));
        $mock->expects($this->once())
            ->method('iWantToMockThis')
            ->willReturn("Mocked!");

        // The Real value 
        $this->assertEquals(12345,$mock->testFunction());
        // The mocked value
        $this->assertEquals("Mocked!",$mock->iWantToMockThis());

         }
}

Hope this help.