【问题标题】:Stubed object is calling real methods in codeception存根对象在代码接收中调用真实方法
【发布时间】:2015-08-31 20:13:15
【问题描述】:

我正在尝试使用 codeception 和他的 Mock 和 Stub 库运行测试。 发生的事情是,当我尝试使用我的存根运行测试时,它引发了一个在我的真实类中实现的错误。

我认为 Stub 是隔离测试和模拟真实对象的方法。为什么它调用我的真实方法?

<?php

class FirstDegreeTest extends \Codeception\TestCase\Test
{
  /**
   * @var \UnitTester
   */
  protected $tester;

  protected function _before()
  {
    $this->max_threads = 30;
    $this->firstDegree = new AlThread\LoadControl\Measurer\FirstDegree($this->max_threads);

    $sensor = Stub::make("AlThread\LoadControl\Sensor\LoadAvg", array("getSystemLoad", Stub::consecutive(0, 1, -3, 1.1, null)));

    $this->firstDegree->setSensor($sensor);
  }

  public function testMeasure()
  {    
    $this->assertEquals(30, $this->firstDegree->measure());
  }
}
?>

所以当我运行codeception(php codeception.phar run)时:

Time: 487 ms, Memory: 11.25Mb

There was 1 error:

---------
1) Test me (FirstDegreeTest::testMeasure)

  [PHPUnit_Framework_Exception] rewind() expects parameter 1 to be resource, null given
                                                                                                 #1  Codeception\Subscriber\ErrorHandler->errorHandler
#2  /home/AlThread/src/LoadControl/Sensor/LoadAVG.php:42
#3  /home/AlThread/src/LoadControl/Sensor/LoadAVG.php:55
#4  /home/AlThread/src/LoadControl/Sensor/LoadAVG.php:49
#5  /home/AlThread/src/LoadControl/Sensor/LoadAVG.php:61
#6  /home/AlThread/src/LoadControl/Sensor/LoadAVG.php:67
#7  /home/AlThread/src/LoadControl/Sensor/LoadSensor.php:10
#8  /home/AlThread/src/LoadControl/Measurer/LoadMeasurer.php:32
#9  /home/AlThread/tests/unit/FirstDegreeTest.php:31
#10 FirstDegreeTest->testMeasure

FAILURES!
Tests: 3, Assertions: 2, Errors: 1.

那么问题来了:

[PHPUnit_Framework_Exception] rewind() expects parameter 1 to be resource, null given

回溯将我带到 LoadAVG 类的真正实现,在那里我真正调用 rewind() 函数,显然,一旦这个类没有适当的运行环境。

会不会是我以错误的方式考虑存根?

非常感谢。

【问题讨论】:

    标签: php unit-testing codeception


    【解决方案1】:

    Stub::make 的参数错误,它应该是关联数组

    $sensor = Stub::make("AlThread\LoadControl\Sensor\LoadAvg", array("getSystemLoad"=>Stub::consecutive(0, 1, -3, 1.1, null)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多