Mock method from the same class that tested method is using

瘦欲@ 提交于 2020-01-24 14:34:40

问题


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?


回答1:


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;
    }
}



来源:https://stackoverflow.com/questions/48666043/mock-method-from-the-same-class-that-tested-method-is-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!