【问题标题】:How to test functions with PHPUnit in Zend?如何在 Zend 中使用 PHPUnit 测试函数?
【发布时间】:2014-02-10 16:33:41
【问题描述】:

我有一个简单的问题。可能我错过了什么。在 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()。这是实现这一目标的正确方法吗?如何准备好这个测试?

谢谢。

【问题讨论】:

    标签: zend-framework frameworks phpunit


    【解决方案1】:

    当它不是一个动作时,在控制器中测试这些功能并不容易。我会将这样的“业务 - 逻辑”移动到 ServiceClass 或 Model 或其他任何地方并对其进行测试。

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

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

    【讨论】:

      【解决方案2】:

      您根本不需要使用控制器来测试您的功能。您的代码与 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)
             );
          }
      }
      

      只要确保在测试类中包含带有函数的文件

      虽然您确实应该创建某种模型/服务类来包装此功能,而不是创建一个函数。

      【讨论】:

        猜你喜欢
        • 2012-03-04
        • 1970-01-01
        • 1970-01-01
        • 2012-08-16
        • 1970-01-01
        • 2015-07-26
        • 2010-11-30
        • 2011-08-25
        • 1970-01-01
        相关资源
        最近更新 更多