How do I test for an exact Exception message, rather than a substring, with PHPUnit?(如何使用 PHPUnit 测试确切的异常消息,而不是子字符串?)
问题描述
According to the PHPUnit Documentation on @expectedExceptionMessage
, the string must only be a substring of the actual Exception
thrown.
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)));
}
}
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);
}
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.
Is there a way with PHPUnit to expect an exact string, rather than a substring? I hope to avoid the following:
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.");
}
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 测试确切的异常消息,而不是子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 PHPUnit 测试确切的异常消息,而不是子字符串?
基础教程推荐
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01