【问题标题】:PHPUnit Exception [duplicate]PHPUnit异常[重复]
【发布时间】:2013-11-02 06:33:18
【问题描述】:

我有以下创建新用户的代码。我正在使用 PHPUnit 准备测试用例,但是我的代码覆盖率无法覆盖异常情况,即throw new Exception(__CLASS__ . ': Invalid data');.

有人可以告诉我如何使用 assertInstanceOf() 或其他方法覆盖 phpunit 中的异常情况吗?

/**
* Creates a new user
*
* @param string            $email
* @param UserType       $UserType
*
* @return UserID
* @throws Exception If Invalid Data is Provided
*/
static public function Create($email, UserType $UserType)
{
    if (!$UserType instanceof UserType) {
        throw new Exception(__CLASS__ . ': Invalid data');
    }

    $UserID = parent::Create($email, $UserType);

    return $UserID;

}

非常感谢

【问题讨论】:

  • 伙计们,请不要在不知道我到底在寻找什么的情况下就将这篇文章变成重复的帖子。您发布的链接对我没有帮助,因为它没有说明处理类型提示的异常。谢谢
  • 怎么不是重复的?
  • 作为问题的提问者,您可以告诉我们您“究竟在寻找什么”。您还希望如何得到答案?

标签: php unit-testing phpunit


【解决方案1】:

编写一个测试,在其中将其他内容然后是正确类的实例放入参数 $UserType。例如一个字符串:

/**
* @covers MyClass::Create
* @expectedException Exception
*/
public function testCreate() {
    $myTestedInstance->Create('email@example.com', 'invalid param', ....);
}

【讨论】:

  • 值得补充的是,PHPUnit 不允许您针对 \Exception 类进行测试。您必须使用更专业的异常来测试它(例如:\InvalidArgumentException)。
  • @Cyprian,并没有真正明白你想说什么,请详细说明一下。非常感谢
  • 当然。如果您使用泛型类抛出异常:\Exception,那么 PHPUnit 测试将失败并显示以下消息:“InvalidArgumentException:您不能期望泛型异常类。”。这意味着如果你想测试异常,你必须使用更专业的异常类(例如,\InvalidArgumentException 或 \LogicException 或你自己的)。
猜你喜欢
  • 2018-08-21
  • 2014-07-07
  • 2015-02-07
  • 2014-11-07
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2011-08-06
  • 2015-10-17
相关资源
最近更新 更多