bruli
bruli

Reputation: 61

How testing instance of Exception with phpunit

I have this class to testing.

class IpSecurity
{
/** @var array  */
private $ipsAllow;

public function __construct(array $ipsAllow)
{
    $this->ipsAllow = $ipsAllow;
}

/**
 * @param string $clientIp
 *
 * @return NotFoundHttpException
 */
public function checkIp($clientIp)
{
    if (!in_array($clientIp, $this->ipsAllow)) {

        throw new NotFoundHttpException('NOT FOUND');
    }
}
} 

I write a test for testing excettion.

class IpSecurityTest extends \PHPUnit_Framework_TestCase
{
/** @var  IpSecurity */
private $ipSecurity;

private $ipsAllow = array(
    '192.168.200.21'
);

public function setUp()
{
    $this->ipSecurity = new IpSecurity($this->ipsAllow);
}

/**
 * @test
 * @expectedException(Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
 */
public function invalidClientIp()
{
   $this->ipSecurity->checkIp('127.0.0.1');
}
}

This is the test output:

PHPUnit 3.7.37 by Sebastian Bergmann.

Configuration read from /home/pablo/dev/www/app/phpunit.xml

E

Time: 36 ms, Memory: 4.50Mb

There was 1 error:

1) ws\AmneiBundle\Tests\Services\IpSecurityTest::invalidClientIp Symfony\Component\HttpKernel\Exception\NotFoundHttpException: NOT FOUND

I want test the exception class, not if result is a exception.

Upvotes: 0

Views: 306

Answers (1)

Farid Movsumov
Farid Movsumov

Reputation: 12725

You can test it with this code

try
{
    $this->ipSecurity->checkIp('127.0.0.1');
}catch( Exception $e )
{
    if (!($e instanceof NotFoundHttpException)) {
       $this->fail("Unexpected Exception type throwed");
    }
}

Upvotes: 1

Related Questions