phpunit 测试 expectedException 不工作

phpunit testing expectedException not working

我正在尝试测试我的 class 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;
    }
}

这是酒吧 class:

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

我试过在评论区提出 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();
}