How to test that simple case? with Mockery

Published 1 week ago by ayman

How to test that simple case?

class Foo {
    public function m1(){
        return $this->m2();
    }

    private function m2() {
        return 'm2';
    }
}

I need to test m1 and stubs m2 instead of return m2 return diff I use Mockery and phpunit

class FooTest extends TestCase {
    public function testM1()
    {
        $foo = Mochery::mock('Foo');
        $this->assertEquals('diff', $foo->m1());
    }
}
Best Answer (As Selected By ayman)
andonovn

Most probably because the class Foo is under a namespace.

But there is one more issue that I can see now and somehow I've missed in my previous reply. Your m2 method is private. And by default, private methods are not "mockable". The quick and dirty solution to this is to make it protected. So you should end up with something like:

$foo = Mockery::mock(Foo::class)
            ->shouldAllowMockingProtectedMethods()
            ->makePartial();
$foo->shouldReceive('m2')->once()->andReturn('diff');
$this->assertEquals('diff', $foo->m1());

But note that protected/private methods are not meant to be tested/mocked. For detailed explanations, and possible solutions, refer to this StackOverflow question

andonovn
$foo = Mockery::mock('Foo')->makePartial();
$foo->shouldReceive('m2')->once()->andReturn('diff');
ayman
ayman
1 week ago (19,110 XP)

I got an error Method Mockery_0__Foo::m1() does not exist on this mock object

    public function testM1()
    {
        $foo = Mockery::mock('Foo')->makePartial();
        $foo->shouldReceive('m2')->once()->andReturn('diff');
        $this->assertEquals('diff', $foo->m1());
    }
class Foo {
    public function m1(){
        return $this->m2();
    }

    private function m2() {
        return 'm2';
    }
}
andonovn

Most probably because the class Foo is under a namespace.

But there is one more issue that I can see now and somehow I've missed in my previous reply. Your m2 method is private. And by default, private methods are not "mockable". The quick and dirty solution to this is to make it protected. So you should end up with something like:

$foo = Mockery::mock(Foo::class)
            ->shouldAllowMockingProtectedMethods()
            ->makePartial();
$foo->shouldReceive('m2')->once()->andReturn('diff');
$this->assertEquals('diff', $foo->m1());

But note that protected/private methods are not meant to be tested/mocked. For detailed explanations, and possible solutions, refer to this StackOverflow question

Sign In or create a forum account to participate in this discussion.