【问题标题】:PHPUnit overwrite actual method with stubPHPUnit用存根覆盖实际方法
【发布时间】:2015-04-09 17:56:10
【问题描述】:

我刚开始玩 PHPUnit,我想知道是否可以用存根覆盖/替换方法。我对诗侬有一些经验,而诗侬可以做到这一点(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() );
  }

}

?>

【问题讨论】:

    标签: php unit-testing mocking phpunit stub


    【解决方案1】:

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

    更好的方法是将 Foo 的依赖注入 Bar,即。 e.:

    <?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() );
      }
    }
    

    有关 DI 的小教程,请参阅 http://code.tutsplus.com/tutorials/dependency-injection-in-php--net-28146

    【讨论】:

    • 方法调用提供1个参数,但方法签名使用0个参数
    猜你喜欢
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    • 2016-01-21
    • 2021-09-10
    • 2014-06-07
    • 2012-07-19
    相关资源
    最近更新 更多