如果我是正确的,SimpleTest将允许您断言抛出PHP错误。但是,根据文档,我无法弄清楚如何使用它。我想声明我传递给构造函数的对象是 MyOtherObject

的实例
class Object {
    public function __construct(MyOtherObject $object) {
        //do something with $object
    }
}

//...and in my test I have...
public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
    $notAnObject = 'foobar';
    $object = new Object($notAnObject);
    $this->expectError($object);
}

我哪里错了?

有帮助吗?

解决方案

类型提示会抛出E_RECOVERABLE_ERROR,自PHP版本5.2起,它可以被SimpleTest捕获。以下内容将捕获包含文本“必须是”的实例的任何错误。 PatternExpectation的构造函数采用perl正则表达式。

public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
    $notAnObject = 'foobar';
    $this->expectError(new PatternExpectation("/must be an instance of/i"));
    $object = new Object($notAnObject);
}

其他提示

PHP有错误和异常,它们的工作方式略有不同。将错误的类型传递给类型化函数会引发异常。您必须在测试用例中捕获它。例如:

public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
  $notAnObject = 'foobar';
  try {
    $object = new Object($notAnObject);
    $this->fail("Expected exception");
  } catch (Exception $ex) {
    $this->pass();
  }
}

或简单地说:

public function testConstruct_ExpectsAnInstanceOfMyOtherObject() {
  $this->expectException();
  $notAnObject = 'foobar';
  $object = new Object($notAnObject);
}

但请注意,这将在发生异常的行之后停止测试。

事实证明,SimpleTest实际上并不支持这一点。您无法在SimpleTest中捕获致命的PHP错误。类型提示很棒,除了你不能测试它。类型提示会导致致命的PHP错误。

你必须在错误发生之前预料到错误,然后SimpleTest将吞下它并计算一个传递,如果测试结束并且没有错误那么它将失败。 (对于PHP(非致命)错误和异常,它们的expectError和expectException分别以相同的方式起作用。)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top