我有这门课来测试。
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');
}
}
这是测试输出:
Sebastian Bergmann撰写的PHPUnit 3.7.37。
从/home/pablo/dev/www/app/phpunit.xml读取配置
电子
时间:36毫秒,内存:4.50Mb
有1个错误:
1)ws \ AmneiBundle \ Tests \ Services \ IpSecurityTest :: invalidClientIp Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException:NOT FOUND
我想测试异常类,而不是结果是异常。
答案 0 :(得分:1)
您可以使用此代码进行测试
try
{
$this->ipSecurity->checkIp('127.0.0.1');
}catch( Exception $e )
{
if (!($e instanceof NotFoundHttpException)) {
$this->fail("Unexpected Exception type throwed");
}
}