【问题标题】:Mock a public method of the class being tested模拟被测试类的公共方法
【发布时间】:2015-12-17 22:47:15
【问题描述】:

我正在尝试对一个类进行单元测试,其中一个公共方法(方法 1)在其中使用同一类的另一个公共方法(方法 2)。例如

class MyClass {
    public function method1()
    {
        $var = $this->method2();
        // Do stuff with var to get $answer
        return $answer;
    }

    public function method2()
    {
        // Do complex workings out to get $var
        return $var;
    }
}

现在,method2 已经过单元测试,我不想在测试method1 时为其实际调用它建立一个参数。我只想模拟method2 并在我的测试中定义将返回什么。这就是我所拥有的:

function test_method1()
{
    $myClass = new MyClass();

    $mockedMyClass = Mockery::mock('MyClass');
    $mockedMyClass->shouldReceive('method2')->once()->andReturn([1,2,3,4]); // mocked $var returned to be used in the rest of method1

    $answer = $myClass->method1();
    // Assertions
}

显然这不起作用,因为被测试的方法与包含被模拟的方法在同一个类中,因此无法将模拟的类作为依赖项传递。仅模拟 method2 的最佳方法是什么?

【问题讨论】:

  • 每当您觉得需要模拟您正在测试的类的方法时,这表明该类应该一分为二,并单独测试。因为如果您因为“我不想建立论点”而感到需要嘲笑,那么该课程可能做得太多了。

标签: unit-testing phpunit mockery


【解决方案1】:

您可以使用测试框架的Partial Mock 功能,该功能允许您测试标记为模拟的同一类。 例如,假设您修改后的类:

<?php


namespace Acme\DemoBundle\Model;


class MyClass {
    public function method1()
    {
        $var = $this->method2();
        $answer = in_array(3, $var);
        // Do stuff with var to get $answer
        return $answer;
    }

    public function method2()
    {
        // Do complex workings out to get $var
        return array();
    }
}

并测试如下:

<?php
namespace Acme\DemoBundle\Tests;


class MyClassTest  extends \PHPUnit_Framework_TestCase {

    function test_method1()
    {

        $mockedMyClass = \Mockery::mock('Acme\DemoBundle\Model\MyClass[method2]');
        $mockedMyClass->shouldReceive('method2')->once()->andReturn([1,2,3,4]); // mocked $var returned to be used in the rest of method1

        $answer = $mockedMyClass->method1();
        $this->assertTrue($answer);        // Assertions
    }

}

希望有帮助

【讨论】:

    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多