unit-testing - 使用 phpunit 测试多个异常

标签 unit-testing exception phpunit

我是单元测试的新手,编写了以下测试:

/**
 * @expectedException Exception
 */
public function testCantGetInvalidCampsite() {
    $invalidIds = array(300000, "string");
    foreach($invalidIds as $id) {
        $this->campsites->getCampsite($id); // will throw an exception
    }
}

我不确定这是否真的在测试所有无效的 ID,或者只是在遇到第一个异常时立即停止。这是我应该如何测试多个异常,还是我需要将其分成许多不同的测试,或者我应该采用另一种方法吗?

此外,如果我的异常消息是动态生成的,例如“无法检索 ID 为 30000 的记录”,我该如何测试是否生成了正确的动态消息?

最佳答案

我在这种情况下使用的方法是使用 phpunit dataProviders :

class MyTest extends PHPUnit_Framework_TestCase
{
    public function invalidIds()
    {
       return array(
           array(300000),
           array("string")
       );
    }


    /**
     * @dataProvider invalidIds
     * @expectedException Exception
     */
    public function testCantGetInvalidCampsite($invalidId)
    {
        $this->campsites->getCampsite($invalidId); // will throw an exception
    }
}

关于unit-testing - 使用 phpunit 测试多个异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4314142/

相关文章:

c++ - 处理失败的构造函数

php - phpunit 中的 dbunit 没有截断表

PHPUnit 和扩展类

java - 在 Robolectric 测试中注入(inject)模拟

unit-testing - Selenium 的作用是什么?

java - 调用 Java 主函数

java - 什么时候应该让应用程序因为 Java 中的异常(设计问题)而崩溃?

javascript - 如何对 Firefox 57 WebExtensions 进行单元测试?

mongodb - bson.M {} deepequal 似乎无法处理 int32

unit-testing - 我如何在 Laravel 4.1 中对 auth 过滤器进行单元测试?