phpunit不会抛出异常

时间:2011-03-01 16:13:21

标签: php phpunit

phpunit test:

public function testSizeOver64K() {
        try {
            $this->login();
            $scriptname = 'test script4';
            $this->fixture->installScript($scriptname, $this->scripts[$scriptname]);
        }
        catch (Exception $expected) {
            return;
        }
        $this->fail('An expected exception has not been raised.');

    }

它调用的函数方法

function installScript($scriptname, $script, $makeactive = false)
    {
        $this->cmdPutScript($scriptname, $script);

        if ($makeactive)
            $this->cmdSetActive($scriptname);

        return true;
    }
private function cmdPutScript($scriptname, $scriptdata)
    {
        if (self::STATE_TRANSACTION != $this->state) {
            $msg = 'Not currently in TRANSACTION state';
            $code = 1;
            throw new Exception($msg, $code);
        }

        $stringLength = $this->getLineLength($scriptdata);

        $this->doCmd(sprintf("PUTSCRIPT \"%s\" {%d+}\r\n%s", $scriptname, $stringLength, $scriptdata));

        return true;
    }
private function getLineLength($string) {
        if (extension_loaded('mbstring') || @dl(PHP_SHLIB_PREFIX.'mbstring.'.PHP_SHLIB_SUFFIX)) {
            $lenght = mb_strlen($string,'8bit');
            if ( $lenght > 65536 ) {
                $msg = "Script is over 64K";
                throw new Exception($msg);
            }   
            return $lenght;
        } else {
            $lenght = strlen($string);
            if ( $lenght > 65536 ) {
                $msg = "Script is over 64K";
                throw new Exception($msg);
            }   
            return $lenght;
        }
    }

有人可以提示为什么phpunit没有捕获异常吗?

2 个答案:

答案 0 :(得分:3)

使用调试器并逐步执行测试用例,以确保您的代码实际上首先抛出异常。从代码中判断环境是否以导致异常的方式设置是不可能的。


在旁注中,您应该抛出较少的一般异常。您使用的是try/catch,因此以下内容不适用于您手头的问题,但请注意

  

实现GH-88:@ ExpectedException(和setExpectedException())不再接受Exception作为预期的异常类。

请参阅changelog for PHPUnit 3.6https://github.com/sebastianbergmann/phpunit/pull/88

答案 1 :(得分:2)

问题在于你的代码,而且根本不是phpunit。

参见此测试用例:

<?php

function foo() {
    throw new Exception("boom");
}
class MyFooTest extends PHPUnit_Framework_TestCase {

    public function testArguments() {
        try {
            foo();
        } catch (Exception $e) {
            return;
        }
        $this->fail("nope");

    }
}

打印:

 phpunit mep.php
PHPUnit 3.5.12 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 3.00Mb

OK (1 test, 0 assertions)

归结为它的基本功能。如果phpunit会改变任何行为,那将是非常奇怪的