代码之家  ›  专栏  ›  技术社区  ›  Nathan MacInnes

PHPUnit未捕获预期的异常

  •  6
  • Nathan MacInnes  · 技术社区  · 14 年前

    我有一组测试,我想测试我的类是否在正确的时间抛出异常。在本例中,我的类使用了_uget()magic方法,因此我需要测试在检索到无效属性时是否引发异常:

    function testExceptionThrownWhenGettingInvalidProperty() {
      $obj = new MyClass();
      $this->setExpectedException("Property qwerty does not exist");
      $qwerty = $obj->qwerty;
    }
    

    该类按其应有的方式抛出错误,但不只是获得一个通过,而是未捕获异常!

    There was 1 error:
    
    1) QueryTest::testExceptionThrownWhenGettingInvalidProperty
    Exception: Property qwerty does not exist
    

    我以前用过SimpleTest $this->expectException(new Exception("Property qwerty does not exist")); 工作得很好。我知道还有其他方法(@expectedException和try catch),但这个方法应该有效,而且看起来更干净。你知道我怎么做吗?

    2 回复  |  直到 14 年前
        1
  •  13
  •   ircmaxell    14 年前

    它不是在异常中查找文本,而是在查找异常类的名称。。。 Docs

    $this->setExpectedException('Exception');
    

    SPL Exceptions ,或自定义异常类。。。

        2
  •  13
  •   ryeguy    14 年前

    加上ircmaxell的回答,实际上有一种更简单的方法:

    /**
     * @expectedException MyExceptionClass
     * @expectedExceptionMessage Array too small
     */
    public function testSomething()
    {
    }
    

    这个 @expectedException 期望的异常的类名,以及 @expectedExceptionMessage 是预期的异常消息的子字符串(没错,您不必拥有整个消息)。