Skip to content
This repository was archived by the owner on Feb 20, 2023. It is now read-only.

If the Mock Class contain a method named "method", it can not be mock.... #244

Closed
jianfengye opened this issue Aug 3, 2015 · 3 comments
Closed

Comments

@jianfengye
Copy link

the code like that :

<?php

class SomeClass
{
    public function doSomething()
    {
        // Do something
    }

    public function method()
    {
        // Do something.
    }
}

class StubTest extends PHPUnit_Framework_TestCase
{
    public function testStub()
    {
        // Create a stub for the SomeClass class.
        $stub = $this->getMockBuilder('SomeClass')
                     ->getMock();

        // Configure the stub.
        $stub->method('doSomething')
             ->willReturn('foo');

        // Calling $stub->doSomething() will now return
        // 'foo'.
        $this->assertEquals('foo', $stub->doSomething());
    }
}

output:

[vagrant@localhost tests]$ phpunit Examples/MockExample.php
PHPUnit 4.7.7 by Sebastian Bergmann and contributors.

PHP Fatal error:  Call to a member function willReturn() on a non-object in /vagrant/develop/vendor/hades/framework/tests/Examples/MockExample.php on line 26

Fatal error: Call to a member function willReturn() on a non-object in /vagrant/develop/vendor/hades/framework/tests/Examples/MockExample.php on line 26

What Can I do if my class has a method named "method" ?

@sebastianbergmann
Copy link
Owner

The method() method is just a shortcut that was introduced with #147. When the original object already has a method named method then the mock object API's method() is not added and you have to use the non-shortcut version of the API.

@jianfengye
Copy link
Author

I don't understand how to solve my issue from that post #147

Is My Code change like that :

<?php

class SomeClass
{
    public function doSomething()
    {
        // Do something
    }

    public function method()
    {
        // Do something.
    }
}

class StubTest extends PHPUnit_Framework_TestCase
{
    public function testStub()
    {
        // Create a stub for the SomeClass class.
        $stub = $this->getMockBuilder('SomeClass')
                     ->getMock();

        // Configure the stub.
        $stub->method('doSomething');
        PHPUnit_Framework_TestCase::returnValue('foo'); 
            // ->willReturn('foo');

        // Calling $stub->doSomething() will now return
        // 'foo'.
        $this->assertEquals('foo', $stub->doSomething());
    }
}

but It also not work

@sebastianbergmann
Copy link
Owner

Please read the section "Limitation: Methods named method" on https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.stubs.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants