Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit How to get the REAL return value of mocked method?

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

like image 771
Chris11235 Avatar asked Oct 19 '25 15:10

Chris11235


2 Answers

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

like image 142
gontrollez Avatar answered Oct 21 '25 04:10

gontrollez


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.

like image 45
Matteo Avatar answered Oct 21 '25 06:10

Matteo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!