【问题标题】:PHPUnit store properties on test classPHPUnit 在测试类上存储属性
【发布时间】:2011-07-15 16:48:54
【问题描述】:

我是 PHPUnit 的初学者。

这是我创建的示例测试类:

class NewTest extends PHPUnit_Framework_TestCase
{
    protected $foo;

    function testFirst ()
    {
        $this->foo = true;
        $this->assertTrue($this->foo);
    }

    /**
     * @depends testFirst
     */
    function testSecond ()
    {
        $this->assertTrue($this->foo);
    }
}

执行 testSecond 时,它会抛出一个错误,提示“Undefined property NewTest::$foo”。

为什么会这样? PHPUnit 是否在每次测试执行后清除新属性?有没有办法在测试中设置一个属性,以便在同一测试类的其他测试中可以访问它?

【问题讨论】:

    标签: php testing properties phpunit


    【解决方案1】:

    通常,您希望避免一项测试影响另一项测试。这可以确保测试是干净的并且始终有效,而不是在 test1 创建的某些边缘情况下。

    【讨论】:

      【解决方案2】:

      您正在 testFirst() 方法中设置 foo 属性。 PHPUnit 将在测试之间重置环境/如果每个测试方法没有 @depends 注释,则为每个测试方法创建一个新的“NewTest”实例),所以如果你想将 foo 设置为 true 你必须重新创建依赖测试中的该状态或使用setup() 方法。

      setup() (docs):

      class NewTest extends PHPUnit_Framework_TestCase
      {
          protected $foo;
          protected function setup()
          {
              $this->foo = TRUE;
          }
          function testFirst ()
          {
              $this->assertTrue($this->foo);
          }
          /**
           * @depends testFirst
           */
          function testSecond ()
          {
              $this->assertTrue($this->foo);
          }
      }
      

      @depends (docs):

      class NewTest extends PHPUnit_Framework_TestCase
      {
          protected $foo;
          function testFirst ()
          {
              $this->foo = TRUE;
              $this->assertTrue($this->foo);
              return $this->foo;
          }
          /**
           * @depends testFirst
           */
          function testSecond($foo)
          {
              $this->foo = $foo;
              $this->assertTrue($this->foo);
          }
      }
      

      以上都应该通过。

      编辑 不得不删除@backupGlobals 解决方案。这是完全错误的。

      【讨论】:

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