How do I test for an exact Exception message, rather than a substring, with PHPUnit?

后端 未结 6 1719
难免孤独
难免孤独 2021-01-12 07:14

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

In

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 07:27

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

提交回复
热议问题