Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SimpleTest:如何断言抛出了PHP错误?_Php_Unit Testing_Simpletest - Fatal编程技术网

SimpleTest:如何断言抛出了PHP错误?

SimpleTest:如何断言抛出了PHP错误?,php,unit-testing,simpletest,Php,Unit Testing,Simpletest,如果我是正确的,SimpleTest将允许您断言抛出PHP错误。然而,根据文档,我不知道如何使用它。我想断言我传递给构造函数的对象是MyOtherObject class Object { public function __construct(MyOtherObject $object) { //do something with $object } } //...and in my test I have... public function testCon

如果我是正确的,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);
}

哪里出了问题?

PHP既有错误也有异常,它们的工作原理略有不同。向typehinted函数传递错误的类型将引发异常。您必须在测试用例中捕捉到这一点。例如:

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将吞下它并计算通过次数,如果测试结束时没有错误,那么它将失败。(对于PHP(非致命)错误和异常,expectError和expectException的作用是相同的。)

事实证明,SimpleTest实际上并不支持这一点。在SimpleTest中无法捕获致命的PHP错误。类型暗示很好,除非你不能测试它。类型提示抛出致命的PHP错误。

类型提示抛出E_可恢复的错误,自PHP版本5.2以来,SimpleTest可以捕获该错误。下面将捕获包含文本“必须是的实例”的任何错误。PatternExpection的构造函数采用perl正则表达式

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

从PHP版本5.2开始,SimpleTest可以捕获类型暗示错误。看我的答案。我还没有证实这一点,所以我只是假设这是真的。谢谢你的回答!我没有投你反对票。但是,我想我应该提到为什么我认为有人会否决它:这个答案与“例外”有关,而不是“错误”。当类型提示选择错误的类型时,它会抛出一个“错误”,而不是一个“异常”。