【问题标题】:PHPUnit - using assertions in external objectPHPUnit - 在外部对象中使用断言
【发布时间】:2015-12-08 09:52:24
【问题描述】:

我正在开发一个将测试导出为 PHP/PHPUnit 的工具,但我遇到了一个小问题。简单解释一下,测试脚本仅包含对 actionwords 对象的调用,该对象包含测试的所有逻辑(以便从不同的测试场景中考虑各种步骤)。 一个例子可能更清楚:

require_once('Actionwords.php');

class CoffeeMachineHiptestPublisherSampleTest extends PHPUnit_Framework_TestCase {
  public $actionwords = new Actionwords();


  public function simpleUse() {
    $this->actionwords->iStartTheCoffeeMachine();
    $this->actionwords->iTakeACoffee();
    $this->actionwords->coffeeShouldBeServed();
  }
}

coffeeShouldBeServed 方法中,我需要运行一个断言,但这是不可能的,因为 Actionwords 类没有扩展 PHPUnit_Framework_TestCase(我不确定它应该,它不是一个测试用例,只是一个一组助手)。

目前我找到的解决方案是将测试对象传递给动作词并使用断言的引用,类似这样。

class CoffeeMachineHiptestPublisherSampleTest extends PHPUnit_Framework_TestCase {
  public $actionwords;

  public function setUp() {
    $this->actionwords = new Actionwords($this);
  }
}

class Actionwords {
  var $tests;

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

  public function coffeeShouldBeServed() {
    $this->tests->assertTrue($this->sut->coffeeServed);
  }
}

它工作得很好,但我觉得它不是很优雅。我不是 PHP 开发人员,所以可能会有一些更好的解决方案,感觉更“php-ish”。

提前致谢, 文森特

【问题讨论】:

    标签: php phpunit


    【解决方案1】:

    断言方法是静态的,因此您可以使用PHPUnit_Framework_Assert::assertEquals(),例如。

    【讨论】:

    • 完美,我之前应该检查过。所有的例子都在使用 $this->assertSomething 所以我认为我必须在一个测试类中
    猜你喜欢
    • 2018-11-27
    • 2017-02-17
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2016-09-14
    • 2014-08-11
    相关资源
    最近更新 更多