If you're running on PHP 5.5+, you can use ::class
resolution to obtain the name of the class with expectException
/setExpectedException
. This provides several benefits:
- The name will be fully-qualified with its namespace (if any).
- It resolves to a
string
so it will work with any version of PHPUnit. - You get code-completion in your IDE.
- The PHP compiler will emit an error if you mistype the class name.
Example:
namespace \My\Cool\Package;
class AuthTest extends \\PHPUnit_Framework_TestCase\PHPUnit_Framework_TestCase
{
public function testLoginFailsForWrongPassword()
{
$this->expectException(WrongPasswordException::class);
Auth::login('Bob', 'wrong');
}
}
PHP compiles
WrongPasswordException::class
into
"\My\Cool\Package\WrongPasswordException"
without PHPUnit being the wiser.
Note: PHPUnit 5.2 introduced
expectException
as a replacement forsetExpectedException
.