如何使用PHPUnit测试确切的Exception消息而不是子字符串? [英] How do I test for an exact Exception message, rather than a substring, with PHPUnit?

查看:118
本文介绍了如何使用PHPUnit测试确切的Exception消息而不是子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

According to the PHPUnit Documentation on @expectedExceptionMessage, the string must only be a substring of the actual Exception thrown.

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

In one of my validation methods, an array item is pushed for each error that occurs, and the final Exception message is displayed by imploding the array of errors.

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测试中方法我检查不同的组合。

The problem I have here is that in the PHPUnit test method I check for different combinations. This causes tests to pass that I intend to fail.

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

Exception的字符串消息实际上是 a< b。b< c。 ,但是此测试仍然通过。我打算使该测试失败,因为消息与我所期望的不完全相同。

The string of the Exception message is actually "a < b. b < c." but this test still passes. I intend for this test to fail because the message is not exactly what I expect.

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.");
}


推荐答案

发布此问题时,PHPUnit v3.7尚未解决此问题。较新的版本具有新的 @expectedExceptionMessageRegExp 选项,可用于添加正则表达式以匹配

When this question was posted, PHPUnit v3.7 didn't have a solution to this problem. Newer versions have a new @expectedExceptionMessageRegExp option that you can use to add a regular expression to match the exception message against.

您的案例,使用 ^ $ 强制字符串完全符合预期,可以看起来像这样:

Your case, using ^ and $ to force the string to be exactly what is expected, could look like this:

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

这篇关于如何使用PHPUnit测试确切的Exception消息而不是子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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