Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用phpunit测试异常实例_Phpunit - Fatal编程技术网

如何使用phpunit测试异常实例

如何使用phpunit测试异常实例,phpunit,Phpunit,我有这门课要考 class IpSecurity { /** @var array */ private $ipsAllow; public function __construct(array $ipsAllow) { $this->ipsAllow = $ipsAllow; } /** * @param string $clientIp * * @return NotFoundHttpException */ public function checkIp($cl

我有这门课要考

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');
    }
}
} 
我写了一个测试来测试异常

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');
}
}
这是测试输出:

塞巴斯蒂安·伯格曼的PHPUnit 3.7.37

从/home/pablo/dev/www/app/phpunit.xml读取配置

E

时间:36毫秒,内存:4.50Mb

有1个错误:

1) ws\AmneiBundle\Tests\Services\IpSecurityTest::invalidClientIp Symfony\Component\HttpKernel\Exception\NotFoundHttpException:未找到


我想测试exception类,而不是测试结果是否为异常。

您可以使用此代码测试它

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

我认为对于这种情况,我可以使用$this->assertInstanceOf,但效果不好。看起来PHPUnit在读取注释时找不到异常类。确保它可以自动加载