【问题标题】:Testing PHPUnit to test a "__construct() must be an instance of .." does not recognize exception测试 PHPUnit 以测试“__construct() 必须是 .. 的实例”不识别异常
【发布时间】:2015-03-26 10:20:57
【问题描述】:

我有以下代码来测试类构造函数是否会触发异常但 PHPUnit 测试失败。我想弄清楚我做错了什么。

/** @test */
public function should_require_instance_of_uuid()
{
    $this->setExpectedException('Exception');
    $id = new BusinessPartnerId;
}

PHPunit 给出以下错误: 有 1 个错误: 1)Tests\Domain\Model\Common\BusinessPartner\BusinessPartnerIdTest::should_require_instance_of_uuid 传递给 Domain\Model\Common\BusinessPartner\BusinessPartnerId::__construct() 的参数 1 必须是 Rhumsaa\Uuid\Uuid 的实例,没有给出,在第 14 行的 tests/Comain/Model/Common/BusinessPartner/BusinesPartnerIdTest.php 中调用并定义

域/模型/通用/BusinessPartner/BusinessPartnerId.php:20 测试/域/模型/Common/BusinessPartner/BusinesPartnerIdTest.php:14

我不确定为什么这个测试没有通过?我也试过: $this->setExpectedException('InvalidArgumentException');

【问题讨论】:

    标签: php phpunit


    【解决方案1】:

    你的测试应该看起来:

    如果你有课:

    class Stack
    {
        public function __construct(\Model $model)
        {
        }
    }
    

    然后测试:

    /**
     * @test
     */
    public function shouldCheckInstance()
    {
        try {
            new Stack(null);
        } catch(\Exception $e) {
            $this->assertContains('must be an instance of Model', $e->getMessage());
        }
    }
    

    【讨论】:

      【解决方案2】:

      虽然我没有使用当前的 PHPUnit,但旧版本不允许您捕获基本 Exception,但会捕获您自己对 Exception 类的扩展。此外,异常可能是命名空间的,所以它是 \Exception,而不仅仅是 Exception。

      我还在 doc 块中使用了 @expectedException 来指示我期望的异常。

      /**
       * @test
       * @expectedException \MyNamespace\MyException
       */
      public function shouldCheckInstance()
      {
          new MyClass():
      }
      

      /**
       * @test
       */
      public function shouldCheckInstance()
      {
          $this->setExpectedException('\MyNamespace\MyException');
          new MyClass():
      }
      

      【讨论】:

        猜你喜欢
        • 2014-08-21
        • 2014-07-07
        • 2015-10-17
        • 2016-04-27
        • 1970-01-01
        • 1970-01-01
        • 2018-03-31
        • 2013-04-14
        • 2011-03-29
        相关资源
        最近更新 更多