PHPUnit断言抛出异常? [英] PHPUnit assert that an exception was thrown?

查看:1091
本文介绍了PHPUnit断言抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道是否有一个断言或类似的东西,可以测试是否在正在测试的代码中抛出异常?

解决方案

http://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit。 exceptions.examples.ExceptionTest.php

 <?php 
require_once'PHPUnit / Framework.php ;

class ExceptionTest扩展PHPUnit_Framework_TestCase
{
public function testException()
{
$ this-> expectException(InvalidArgumentException :: class);
//或PHPUnit 5.2
// $ this-> setExpectedException(InvalidArgumentException :: class);

//...然后添加生成异常的测试代码
exampleMethod($ anInvalidArgument);
}
}


Does anyone know whether there is an assert or something like that which can test whether an exception was thrown in the code being tested?

解决方案

http://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.exceptions.examples.ExceptionTest.php

<?php
require_once 'PHPUnit/Framework.php';

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    public function testException()
    {
        $this->expectException(InvalidArgumentException::class);
        // or for PHPUnit < 5.2
        // $this->setExpectedException(InvalidArgumentException::class);

        //...and then add your test code that generates the exception 
        exampleMethod($anInvalidArgument);
    }
}

这篇关于PHPUnit断言抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆