phpunit测试expectException无法正常工作

前端之家收集整理的这篇文章主要介绍了phpunit测试expectException无法正常工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试测试我的类InvalidArgumentException,但我得到了

Tests\BarTest::should_receive_parameter Missing argument 1 for
Itdc\Foo\Bar::__construct(),called in
/mypath/foo/tests/BarTest.PHP on line 10 and
defined

这是我使用的测试(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
    }
}

我试图在注释部分puth setExpectedException,也试图使用InvalidArgumentException,但没有运气.

任何建议我做错了将不胜感激.

如果你直接捕获它,你可以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();
}
原文链接:https://www.f2er.com/php/445230.html

猜你在找的PHP相关文章