PHPUnit测试中的expectedException无法正常工作

6

我正在尝试测试我的InvalidArgumentException类,但是我遇到了以下问题:

Tests\BarTest::should_receive_parameter缺失第1个参数,在/mypath/foo/tests/BarTest.php的第10行调用了Itdc\Foo\Bar::__construct()函数,但未定义

这是我使用的测试(BarTest.php)文件:

<?php namespace Tests;
use Itdc\Foo\Bar;
class BarTest extends \PHPUnit_Framework_TestCase {
    /** @test */
    public function should_receive_parameter() {
        $this->setExpectedException('Exception');
        $id = new Bar;
    }
}

这是Bar类:
<?php namespace Itdc\Foo;
class Bar {
    public function __construct($a) {
        // do something
    }
}

我已经尝试将setExpectedException放在注释部分,也尝试使用InvalidArgumentException,但没有成功。

如果你有任何建议,我将不胜感激。

1个回答

4
如果您直接捕获它,可以使用var_dump()来输出异常信息。
/** @test */
public function shouldThrowException() {
  try {
    new Foo();
  } catch (\Exception $e) {
    var_dump($e);
  }
}

输出:

class PHPUnit_Framework_Error_Warning#19 (9) {
  ...

因此,这里的源代码不会触发异常,而是错误。PHPUnit将错误转换为特定的异常。但它不包括在断言中。

尝试使用特定的异常名称:

/** @test */
public function shouldThrowException() {
  $this->setExpectedException('PHPUnit_Framework_Error_Warning');
  new Foo();
}

如果你和我一样偶然看到了这篇帖子,更新的phpunit使用了以下代码:$this->expectException(\Exception::class); $this->expectExceptionCode('the_expected_code'); $this->expectExceptionMessage('Wrong exception');参考链接:https://stackoverflow.com/questions/61296581/how-to-use-expectexception-in-phpunit - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接