php - 如何使用 PHPUnit 测试确切的异常消息,而不是子字符串?

标签 php unit-testing exception-handling phpunit php-5.3

根据PHPUnit Documentation@expectedExceptionMessage , 该字符串只能是实际 Exception 的子字符串抛出。

在我的一种验证方法中,为发生的每个错误推送一个数组项,最后的 Exception通过爆破错误数组来显示消息。

class MyClass
{
    public function validate($a, $b, $c, $d)
    {
        if($a < $b) $errors[] = "a < b.";
        if($b < $c) $errors[] = "b < c.";
        if($c < $d) $errors[] = "c < d.";

        if(count($errors) > 0) throw new \Exception(trim(implode(" ", $errors)));
    }
}

我在这里遇到的问题是,在 PHPUnit 测试方法中,我检查了不同的组合。这会导致我打算失败的测试通过。

/**
 * @expectedException \Exception
 * @expectedExceptionMessage a < b.
 */
public function testValues_ALessBOnly()
{
    $myClass = new MyClass()
    $myClass->validate(1, 2, 4, 3);
}

Exception 的字符串消息实际上是"a < b. b < c."但这个测试仍然通过。我打算让这个测试失败,因为消息与我预期的不完全一样。

有没有办法让 PHPUnit 期待一个精确的字符串,而不是一个子字符串?我希望避免以下情况:

public function testValues_ALessBOnly()
{
    $myClass = new MyClass()
    $fail = FALSE;

    try
    {
        $myClass->validate(1, 2, 4, 3);
    }
    catch(\Exception $e)
    {
        $fail = TRUE;
        $this->assertEquals($e->getMessage(), "a < b.";
    }

    if(!$fail) $this->fail("No Exceptions were thrown.");
}

最佳答案

您可以使用 $this->expectExceptionMessage() 来处理这个问题。

例子:

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Some error message');

关于php - 如何使用 PHPUnit 测试确切的异常消息,而不是子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18647836/

相关文章:

php - CI 商家的商品名称/描述

scala - 同一个 Play 项目中的 Gatling 负载测试和 ScalaTest 单元测试

node.js - 运行测试时“描述未定义”

c++ - 解决将对象传递给抛出的函数时可能发生的内存泄漏

php - 使用 PHP 和新的 Twitter API

php - 在线申请中的灵活数据

javascript - FlexSlider 轮播在第一张幻灯片中滑动所有图像 - WordPress

c++ - Qt单元测试框架中的 "0 skipped, 0 blacklisted"是什么意思?

exception - mips异常处理beq无法正常工作

c# - C# 中的一般异常处理