PHPUnit 用 stub 覆盖实际方法

标签 php unit-testing mocking phpunit stub

我刚刚开始使用 PHPUnit,我想知道是否可以用 stub 覆盖/替换方法。我有一些使用Sinon的经验,使用Sinon这是可能的( http://sinonjs.org/docs/#stubs )

我想要这样的东西:

<?php

class Foo {

  public $bar;

  function __construct() {
    $this->bar = new Bar();
  }

  public function getBarString() {
    return $this->bar->getString();
  }

}

class Bar {

  public function getString() {
    return 'Some string';
  }

}



class FooTest extends PHPUnit_Framework_TestCase {

  public function testStringThing() {
    $foo = new Foo();

    $mock = $this->getMockBuilder( 'Bar' )
      ->setMethods(array( 'getString' ))
      ->getMock();

    $mock->method('getString')
      ->willReturn('Some other string');

    $this->assertEquals( 'Some other string', $foo->getBarString() );
  }

}

?>

最佳答案

这不起作用,您将无法在 Foo 实例内模拟 Bar 实例。 Bar 在 Foo 的构造函数内实例化。

更好的方法是将 Foo 的依赖注入(inject)到 Bar,即。例如:

<?php

class Foo {

  public $bar;

  function __construct(Bar $bar) {
    $this->bar = $bar;
  }

  public function getBarString() {
    return $this->bar->getString();
  }
}

class Bar {

  public function getString() {
    return 'Some string';
  }

}

class FooTest extends PHPUnit_Framework_TestCase {

  public function testStringThing() {

    $mock = $this->getMockBuilder( 'Bar' )
      ->setMethods(array( 'getString' ))
      ->getMock();

    $mock->method('getString')
      ->willReturn('Some other string');

    $foo = new Foo($mock); // Inject the mocked Bar instance to Foo

    $this->assertEquals( 'Some other string', $foo->getBarString() );
  }
}

参见http://code.tutsplus.com/tutorials/dependency-injection-in-php--net-28146 DI 的小教程。

关于PHPUnit 用 stub 覆盖实际方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28419169/

相关文章:

php - 如何从字符串中替换一个左边的字符?

php - 从 Flex 打开自定义 IE 窗口或窗口可以自定义自身吗?

PHP/MYSQL最快搜索解决方案

php - 在线酒店预订系统,同时预订?

javascript - 当我使用 Jest 从模拟的 axios 调用返回一些响应时变得不确定

python - 测试类中所有测试用例的模拟导入方法

c# - 使用最小起订量模拟通用存储库

unit-testing - 单元测试 - 如何测试返回随机输出的函数?

unit-testing - 如何访问 CakePHP 2 测试用例中的夹具数据?

firebase - 使用 Jest、Firebase 和 React-Native 运行测试