Reputation: 341
I have the following code to test if the class constructor will fire the exception but PHPUnit test fail on it. I am trying to figure out what I am doing wrong.
/** @test */
public function should_require_instance_of_uuid()
{
$this->setExpectedException('Exception');
$id = new BusinessPartnerId;
}
PHPunit gives the following error: There was 1 error: 1) Tests\Domain\Model\Common\BusinessPartner\BusinessPartnerIdTest::should_require_instance_of_uuid Argument 1 passed to Domain\Model\Common\BusinessPartner\BusinessPartnerId::__construct() must be an instance of Rhumsaa\Uuid\Uuid, none given, called in tests/Comain/Model/Common/BusinessPartner/BusinesPartnerIdTest.php on line 14 and defined
Domain/Model/Common/BusinessPartner/BusinessPartnerId.php:20 tests/Domain/Model/Common/BusinessPartner/BusinesPartnerIdTest.php:14
I am not sure why this test is not passing? I have also tried:
$this->setExpectedException('InvalidArgumentException');
Upvotes: 0
Views: 1667
Reputation: 11250
While I have not worked with the current PHPUnit, the older versions did not allow you to capture the basic Exception, but would capture your own extension to the Exception class. Also, the exception is likely namespaced, so it is \Exception, not just Exception.
I also used the @expectedException in the doc block to indicate what exception I was expecting.
/**
* @test
* @expectedException \MyNamespace\MyException
*/
public function shouldCheckInstance()
{
new MyClass():
}
or
/**
* @test
*/
public function shouldCheckInstance()
{
$this->setExpectedException('\MyNamespace\MyException');
new MyClass():
}
Upvotes: 1
Reputation: 6204
You test should looks:
If you have class:
class Stack
{
public function __construct(\Model $model)
{
}
}
Then test:
/**
* @test
*/
public function shouldCheckInstance()
{
try {
new Stack(null);
} catch(\Exception $e) {
$this->assertContains('must be an instance of Model', $e->getMessage());
}
}
Upvotes: 2