如何在Zend中使用PHPUnit测试函数?

时间:2014-01-21 07:45:26

标签: zend-framework frameworks phpunit

我有一个简单的问题。可能我错过了一些东西。是否有可能在Zend Framework中测试正常功能而不是动作?

例如,我想为此函数运行测试:

public function isMature($age){
    if($age>=18) true;
        else false;
}

位于IndexController中。我试过

$this->indexController = new IndexController();
$this->assertFalse($this->indexController->isMature(5));

但PHPUnit说我必须将Zend_Controller_Request_Abstract的实例传递给__construct()。这是实现这个目标的正确方法吗?如何以良好的方式准备这个测试?

感谢。

2 个答案:

答案 0 :(得分:1)

当控制器不是动作时,测试这些功能并不容易。我会将这样的“业务 - 逻辑”转移到ServiceClass或Model或者其他任何东西并测试它。

class My_Age_Service()
{
    public function isMature($age){
       if($age>=18) true;
        else false;
    }
}

要对单元测试控制器操作,请查看“Zend_Test_PHPUnit_ControllerTestCase” Zend Controller Tests

答案 1 :(得分:1)

您根本不需要使用控制器来测试您的功能。您的代码与Zend Framework无关,因此您无需关心控制器。

class MatureTest extends PHPUnit_Framework_TestCase {
    /**
     * @dataProvider dataIsMature
     */
    public function TestIsMature($age, $expected) {
       $this->assertSame($expected, isMature($age));
    }

    public function dataIsMature() {
       return array(
            'mature' => array(18, true),
            'not mature' => array(17, false),
            'really mature' => array(99, true)
       );
    }
}

请确保您在测试类中包含该函数的文件

虽然你真的应该创建某种模型/服务类来包装这个功能,而不是创建一个函数。

相关问题