如何检查PHPUnit正确抛出的异常?

时间:2012-05-04 11:03:03

标签: php exception phpunit testcase

我在CalTest类的Cal类中有div()有以下方法来测试div()。

public fucnction div($a,$b){
   if($b == 0){
    throw new Exception("Divided by zero");
   }
   return $a/$b
}

我只能传递testDiv()但是传递testDiv2()。

enter image description here

我想要检查使用PHPUnit正确抛出的exeption。我在这里失踪了什么?非常感谢您的帮助。谢谢!

enter image description here

6 个答案:

答案 0 :(得分:4)

您的第二个屏幕截图(有错误的屏幕截图)

  

“@ expectedException异常”

而第三个

  

@expectedException InvalidArgumentException

你真的还得错吗?你保存文件了吗?


适合我:

Foo.php

<?php

class Foo
{
    static function t()
    {
        throw new InvalidArgumentException('Hi there');
    }
}

?>

FooTest.php

<?php
require_once 'Foo.php';
class FooTest extends PHPUnit_Framework_TestCase
{
    /**
     * @expectedException InvalidArgumentException
     */
    public function testT()
    {
        Foo::t();
    }
}

?>

结果

$ phpunit .
PHPUnit 3.6.10 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 5.25Mb

OK (1 test, 1 assertion)

答案 1 :(得分:3)

刚刚遇到同样的问题。出于某种原因,PHPUnit不允许您将expectedException设置为一般异常,我不知道为什么。我个人选择抛出自定义的异常代码,而不是每次我想区分异常时都要创建一个新的异常类。

以下是我如何解决这个问题:

/**
 * @expectedException Test_Exception
 */
public function testDivByZero()
{
    try {
        // Fyi you don't need to do an assert test here, as we are only testing the exception, so just make the call
        $result = $this->object->div(1,0);
    } catch (Exception $e) {
        if ('Exception' === get_class($e)) {
            throw new Test_Exception($e->getMessage(), $e->getCode());
        }
    }
 }

 // Test_Exception.php
 class Test_Exception extends Exception
 {
     public function __construct($message = null, $code = 0, Exception $previous = null)
     {
         parent::__construct($message, $code, $previous);
     }
 }

这将允许您按照自己的方式设计代码,并抛出“泛型”异常。基本上它只测试Exception类,如果它是通用的,则将其重新包装为另一个异常; Test_Exception。

- 更新 -

昨天发现他们在当前的“主”分支中有removed the generic exception restriction,这将是3.7。显然,首席工程师不想修补3.6。

答案 2 :(得分:2)

在PHPUnit抛出的异常中这样说:

  

除了通用异常类之外,您不能这样做。

让您的课程抛出more detailed Exceptions,并进一步指定您在单元测试中期望的异常类型。

答案 3 :(得分:2)

此问题已在PHPUnit 3.7.x

中修复

您可以在PHPUnit 3.7.x中使用以下通用异常

    /**
     * @expectedException Exception     
     */

答案 4 :(得分:0)

你可以做这样的事情

编写单元测试,以便注入触发异常所需的值,然后

//断言 $这 - &GT; assertTrue($这 - &GT; setExpectedException( 'PHPUnit_Framework_ExpectationFailedException'));

答案 5 :(得分:0)

我创建了一个父类方法来完成它。事实上,这门课程来自laravel,但在任何情况下都有效。

这个方法很酷的部分是在PHP中使用匿名函数

<?php
class TestCase 
         /* if you are not using laravel, you dont need this 
        extends Illuminate\Foundation\Testing\TestCase */ {

    protected function assertThrows( $function , $classException = "/Exception" )
    {
        try 
        {
            // Anonymous functions FTW
            $function();
        }
        catch( /Exception $objException )
        {
            // the assertInstanceOf should solve from here but
            // it is not working that great
            // @see http://stackoverflow.com/questions/16833923/phpunit-assertinstanceof-not-working
            if( $objException instanceof $classException ) {
                return $this->assertTrue( true );
            } else {
                // this will throw a error with a cool message
                return $this->assertEquals( $classException  , get_class( $objException ));
            }
        }
        // no exception happened.
        return $this->fail( "Exception " . $classException . " expected." );
    }

}

class LanguageTest extends TestCase {

    /**
     * Test the translation
     *
     * @return void
     */
    public function testTranslation()
    {
        // this test may be ok
        $this->assertThrows( 
            function(){ throw new Full\Path\Exception(":("); }, 
            "Full\Path\Exception" );

        // this test may fail 
        $this->assertThrows( 
            function(){ return 1 + 1; }, 
            "Some\Excepted\Exception" );

        // this test may work 
        $this->assertThrows( 
            function(){ throw new Exception( "sad" ); }
        );
    }

}