【问题标题】:How can I replace A PHP class by PHPUnit stub?如何用 PHPUnit 存根替换 PHP 类?
【发布时间】:2016-08-10 03:52:05
【问题描述】:

这是我等待 phpunit 测试的函数:

<?php
class Dog
{
    public function born()
    {
        $a = new Action();
        $rs = $a->talk();
        return $rs;
    }
}

类 Action 是:

class Action
{
    public function talk()
    {
        return "true";
    }
}

测试函数是:

public function testStub()
{
    $stub = $this->getMockBuilder('Action')
        ->getMock();
    $stub->method('talk')
        ->willReturn('false');
    var_dump($stub->talk()); // "false"

    $dog = new Dog();

    //[How can the born method invoke the stub method ?]
    var_dump($dog->born()); // "true" [I think it should be "false",but it isn't]
}

现在,如何使用存根类来替换 Action 类?

感谢您的帮助。

【问题讨论】:

标签: phpunit stub


【解决方案1】:

您的代码当前的编写方式无法将Action 替换为测试替身。代码需要重构,以便您可以注入 Action 实例。然后您可以使用测试替身而不是真正的Action 实例。

【讨论】:

  • 有帮助!非常感谢。
猜你喜欢
  • 2017-04-16
  • 2015-02-18
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 2011-12-26
相关资源
最近更新 更多