来自与测试方法相同的类的模拟方法 [英] Mock method from the same class that tested method is using

查看:120
本文介绍了来自与测试方法相同的类的模拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

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

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

在测试中我正在打电话

$fooMock->someMethod()

但是它正在使用原始方法(未模拟)方法otherMethod()并显示错误。

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

您能帮我吗?

推荐答案

使用它作为模板来模拟方法:

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

这篇关于来自与测试方法相同的类的模拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆