来自测试方法的同一类的模拟方法正在使用

时间:2018-02-07 14:15:24

标签: php unit-testing testing codeception mockery

我有以下代码:

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

我正在尝试测试someMethod(),我不想测试otherMethod(),因为它非常复杂并且我有专门的测试 - 在这里我只想模拟它并返回特定值。 所以我试着:

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

并且在测试中我正在呼叫

$fooMock->someMethod()

但它使用原始(非模拟)方法otherMethod()并打印错误。

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

你能帮我吗?

1 个答案:

答案 0 :(得分:1)

使用此模板模拟方法:

<?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.
        return false;
    }
}

enter image description here