问题
I am trying to test my class for InvalidArgumentException but I get
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
This is the test (BarTest.php) file I use:
<?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;
}
}
This is Bar class:
<?php namespace Itdc\Foo;
class Bar {
public function __construct($a) {
// do something
}
}
I have tried to puth setExpectedException in comment section, also tried to use InvalidArgumentException, but no luck.
Any suggetions what I am doing wrong would be appreciated.
回答1:
If you catch it directly you can var_dump() the exception.
/** @test */
public function shouldThrowException() {
try {
new Foo();
} catch (\Exception $e) {
var_dump($e);
}
}
Output:
class PHPUnit_Framework_Error_Warning#19 (9) {
...
So here the source does not trigger an exception but an error, PHPUnit converts the error into a specific exception. But it does not include it in the assertions.
Try using the specific exception name:
/** @test */
public function shouldThrowException() {
$this->setExpectedException('PHPUnit_Framework_Error_Warning');
new Foo();
}
来源:https://stackoverflow.com/questions/29940377/phpunit-testing-expectedexception-not-working