在PHPUnit中使用test_helpers扩展时,如何设置返回值

问题描述

|| 最近,我承担了为单元测试设置系统的任务,但是我遇到了一个问题。 http://sebastian-bergmann.de/archives/885-Stubbing-Hard-Coded-Dependencies.html上的示例的设置与我要测试的代码非常相似。我唯一需要做的就是让have0返回我选择的东西。 更新 我尝试将ѭ1设置为某个变量,然后设置返回值。但是PHPUnit似乎没有注意到我设置的变量和返回值。我假设这是因为该变量从未在任何地方使用。但是,随着代码的设置,无法将模拟对象传递给foo,因此它知道使用该对象而不是实际的Bar类。我已经在Foo和Bar类中添加了一些内容,以便于参考。原始的Bar类返回*,但我希望它从模拟类返回**。 此测试不是必须使用
set_new_overload()
,但到目前为止,这是我成功模拟Bar的唯一方法
<?PHP
require_once \'Foo.PHP\';

class FooTest extends PHPUnit_Framework_TestCase {

    protected function setUp()
    {
        $mock = $this->getMock(
            \'Bar\',/* name of class to mock     */
            array(\'doSomethingElse\'),/* list of methods to mock   */
            array(),/* constructor arguments     */
            \'BarMock\'                  /* name for mocked class     */
        );

        $mock->expects($this->any())
                 ->method(\"doSomthingElse\")
                 ->will($this->returnValue(\"**\")
        ); 
        set_new_overload(array($this,\'newCallback\'));
    }

    protected function tearDown()
    {
        unset_new_overload();
    }

    protected function newCallback($className)
    {
    switch ($className) {
        case \'Bar\':
                    return \'BarMock\';
        default:
                    return $className;
        }
     }

    public function testDoSomething()
    {
        $foo = new Foo;
        $this->assertTrue($foo->doSomething());
    }
}
?>


<?PHP
require_once \'Bar.PHP\';

class Foo {
    public function doSomething()
    {
        // ...

        $bar = new Bar;
        $bar->doSomethingElse();

        // ...

        return TRUE;
    }
}
?>



<?PHP
class Bar {
    public function doSomethingElse()
    {
        return \'*\';
    }
}
?>
    

解决方法

        模拟类本身不会有任何预期的行为。要将其用作存根(在调用方法Y时执行X),您需要访问创建的
BarMock
实例,但是看起来新的重载并不会给您带来好处。 相反,我将创建一个自定义子类
Bar
,以从
doSomethingElse()
返回您想要的内容。     ,        我不太了解您要在这里做什么,但是: 您正在调用getMock(),但实际上并未分配任何内容 要设置返回值,请参见示例11.2:http://www.phpunit.de/manual/3.5/en/test-doubles.html 您在“ BarMock”中有一些奇怪的空格