0

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.

1
  • 1
    Looks like PHPUnit can't find the Exception class when reading the annotation. Make sure it can be autoloaded
    – gontrollez
    Commented Jul 2, 2014 at 21:13

1 Answer 1

1

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");
    }
}
1
  • I thought that for this case I could use $this->assertInstanceOf, but don't works fine.
    – bruli
    Commented Jul 2, 2014 at 9:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.