Marcin Szymański
Marcin Szymański

Reputation: 141

Mock method from the same class that tested method is using

I have following code:

class Foo() {
    public function someMethod() {
        ...
        if ($this->otherMethod($lorem, $ipsum)) {
            ...
        }
        ...
    }
}

and I'm trying to test the someMethod(), I don't want to test otherMethod() since it's quite complex and I have dedicated tests - here I would only like to mock it and return specific values. So I tried to:

$fooMock = Mockery::mock(Foo::class)
    ->makePartial();
$fooMock->shouldReceive('otherMethod')
    ->withAnyArgs()
    ->andReturn($otherMethodReturnValue);

and in test I'm calling

$fooMock->someMethod()

But it's using the original (not mocked) method otherMethod() and prints errors.

 Argument 1 passed to Mockery_3_Foo::otherMethod() must be an instance of SomeClass, boolean given

Could you help me please?

Upvotes: 3

Views: 2990

Answers (1)

John Dee
John Dee

Reputation: 569

Use this as a template to mock a method:

<?php

class FooTest extends \Codeception\TestCase\Test{

    /**
     * @test
     * it should give Joy
     */
    public function itShouldGiveJoy(){
        //Mock otherMethod:
        $fooMock = Mockery::mock(Foo::class)
           ->makePartial();
        $mockedValue = TRUE;
        $fooMock->shouldReceive('otherMethod')
           ->withAnyArgs()
           ->andReturn($mockedValue);

        $returnedValue = $fooMock->someMethod();
        $this->assertEquals('JOY!', $returnedValue);
        $this->assertNotEquals('BOO!', $returnedValue);
    }
}

class Foo{

    public function someMethod() {
        if($this->otherMethod()) {
            return "JOY!";
        }
        return "BOO!";
    }

    public function otherMethod(){
        //In the test, this method is going to get mocked to return TRUE.
        //that is because this method ISN'T BUILT YET.
        return false;
    }
}

enter image description here

Upvotes: 4

Related Questions