Zend Framework 和 Doctrine 2 - 我的单元测试是不是足够?

Posted

技术标签:

【中文标题】Zend Framework 和 Doctrine 2 - 我的单元测试是不是足够?【英文标题】:Zend Framework and Doctrine 2 - are my unit tests sufficient?Zend Framework 和 Doctrine 2 - 我的单元测试是否足够? 【发布时间】:2013-09-18 07:51:35 【问题描述】:

我对 Zend 和单元测试很陌生。我想出了一个使用 Zend Framework 2 和 Doctrine 的小应用程序。它只有一个模型和控制器,我想对它们运行一些单元测试。

这是我目前所拥有的:

基础学说“实体”类,包含我想在所有实体中使用的方法:

<?php
/**
 * Base entity class containing some functionality that will be used by all
 * entities 
 */

namespace Perceptive\Database;

use Zend\Validator\ValidatorChain;

class Entity

    //An array of validators for various fields in this entity
    protected $validators;

    /**
     * Returns the properties of this object as an array for ease of use. Will
     * return only properties with the ORM\Column annotation as this way we know
     * for sure that it is a column with data associated, and won't pick up any
     * other properties. 
     * @return array 
     */
    public function toArray()
      //Create an annotation reader so we can read annotations
      $reader = new \Doctrine\Common\Annotations\AnnotationReader();

      //Create a reflection class and retrieve the properties
      $reflClass = new \ReflectionClass($this);
      $properties = $reflClass->getProperties();

      //Create an array in which to store the data
      $array = array();

      //Loop through each property. Get the annotations for each property
      //and add to the array to return, ONLY if it contains an ORM\Column
      //annotation.
      foreach($properties as $property)
        $annotations = $reader->getPropertyAnnotations($property);
        foreach($annotations as $annotation)
          if($annotation instanceof \Doctrine\ORM\Mapping\Column)
            $array[$property->name] = $this->$property->name;
          
        
      

      //Finally, return the data array to the user
      return $array;
    

    /**
     * Updates all of the values in this entity from an array. If any property
     * does not exist a ReflectionException will be thrown.
     * @param array $data
     * @return \Perceptive\Database\Entity 
     */
    public function fromArray($data)
      //Create an annotation reader so we can read annotations
      $reader = new \Doctrine\Common\Annotations\AnnotationReader();

      //Create a reflection class and retrieve the properties
      $reflClass = new \ReflectionClass($this);

      //Loop through each element in the supplied array
      foreach($data as $key=>$value)
          //Attempt to get at the property - if the property doesn't exist an
          //exception will be thrown here.
          $property = $reflClass->getProperty($key);

          //Access the property's annotations
          $annotations = $reader->getPropertyAnnotations($property);

          //Loop through all annotations to see if this is actually a valid column
          //to update.
          $isColumn = false;
          foreach($annotations as $annotation)
            if($annotation instanceof \Doctrine\ORM\Mapping\Column)
              $isColumn = true;
            
          

          //If it is a column then update it using it's setter function. Otherwise,
          //throw an exception.
          if($isColumn===true)
            $func = 'set'.ucfirst($property->getName());
            $this->$func($data[$property->getName()]);
          else
            throw new \Exception('You cannot update the value of a non-column using fromArray.');
          
      

      //return this object to facilitate a 'fluent' interface.
      return $this;
    

    /**
     * Validates a field against an array of validators. Returns true if the value is
     * valid or an error string if not.
     * @param string $fieldName The name of the field to validate. This is only used when constructing the error string
     * @param mixed $value
     * @param array $validators
     * @return boolean|string 
     */
    protected function setField($fieldName, $value)
      //Create a validator chain
      $validatorChain = new ValidatorChain();
      $validators = $this->getValidators();

      //Try to retrieve the validators for this field
      if(array_key_exists($fieldName, $this->validators))
        $validators = $this->validators[$fieldName];
      else
        $validators = array();
      

      //Add all validators to the chain
      foreach($validators as $validator)
        $validatorChain->attach($validator);
      

      //Check if the value is valid according to the validators. Return true if so,
      //or an error string if not.
      if($validatorChain->isValid($value))
        $this->$fieldName = $value;
        return $this;
      else
        $err = 'The '.$fieldName.' field was not valid: '.implode(',',$validatorChain->getMessages());
        throw new \Exception($err);
      
    

我的“配置”实体,它代表一个包含一些配置选项的单行表:

<?php
/**
 * @todo: add a base entity class which handles validation via annotations
 * and includes toArray function. Also needs to get/set using __get and __set
 * magic methods. Potentially add a fromArray method?
 */
namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;
use Zend\Validator;
use Zend\I18n\Validator as I18nValidator;
use Perceptive\Database\Entity;


/** 
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class Config extends Entity
    /** 
     * @ORM\Id
     * @ORM\Column(type="integer")
     */
    protected $minLengthUserId;

    /** 
     * @ORM\Id
     * @ORM\Column(type="integer") 
     */
    protected $minLengthUserName;

    /** 
     * @ORM\Id
     * @ORM\Column(type="integer") 
     */
    protected $minLengthUserPassword;

    /** 
     * @ORM\Id
     * @ORM\Column(type="integer") 
     */
    protected $daysPasswordReuse;

    /** 
     * @ORM\Id
     * @ORM\Column(type="boolean") 
     */
    protected $passwordLettersAndNumbers;

    /** 
     * @ORM\Id
     * @ORM\Column(type="boolean") 
     */
    protected $passwordUpperLower;

    /** 
     * @ORM\Id
     * @ORM\Column(type="integer") 
     */
    protected $maxFailedLogins;

    /** 
     * @ORM\Id
     * @ORM\Column(type="integer") 
     */
    protected $passwordValidity;

    /** 
     * @ORM\Id
     * @ORM\Column(type="integer") 
     */
    protected $passwordExpiryDays;

    /** 
     * @ORM\Id
     * @ORM\Column(type="integer") 
     */
    protected $timeout;

    // getters/setters
    /**
     * Get the minimum length of the user ID
     * @return int 
     */
    public function getMinLengthUserId()
        return $this->minLengthUserId;
    

    /**
     * Set the minmum length of the user ID
     * @param int $minLengthUserId
     * @return \Application\Entity\Config This object
     */
    public function setMinLengthUserId($minLengthUserId)
        //Use the setField function, which checks whether the field is valid,
        //to set the value.
        return $this->setField('minLengthUserId', $minLengthUserId);
    

    /**
     * Get the minimum length of the user name
     * @return int 
     */
    public function getminLengthUserName()
      return $this->minLengthUserName;
    

    /**
     * Set the minimum length of the user name
     * @param int $minLengthUserName
     * @return \Application\Entity\Config 
     */
    public function setMinLengthUserName($minLengthUserName)
      //Use the setField function, which checks whether the field is valid,
      //to set the value.
      return $this->setField('minLengthUserName', $minLengthUserName);
    

    /**
     * Get the minimum length of the user password
     * @return int 
     */
    public function getMinLengthUserPassword()
      return $this->minLengthUserPassword;
    

    /**
     * Set the minimum length of the user password
     * @param int $minLengthUserPassword
     * @return \Application\Entity\Config 
     */
    public function setMinLengthUserPassword($minLengthUserPassword)
      //Use the setField function, which checks whether the field is valid,
      //to set the value.
      return $this->setField('minLengthUserPassword', $minLengthUserPassword);
    

    /**
     * Get the number of days before passwords can be reused
     * @return int 
     */
    public function getDaysPasswordReuse()
      return $this->daysPasswordReuse;
    

    /**
     * Set the number of days before passwords can be reused
     * @param int $daysPasswordReuse
     * @return \Application\Entity\Config 
     */
    public function setDaysPasswordReuse($daysPasswordReuse)
      //Use the setField function, which checks whether the field is valid,
      //to set the value.
      return $this->setField('daysPasswordReuse', $daysPasswordReuse);
    

    /**
     * Get whether the passwords must contain letters and numbers
     * @return boolean 
     */
    public function getPasswordLettersAndNumbers()
      return $this->passwordLettersAndNumbers;
    

    /**
     * Set whether passwords must contain letters and numbers
     * @param int $passwordLettersAndNumbers
     * @return \Application\Entity\Config 
     */
    public function setPasswordLettersAndNumbers($passwordLettersAndNumbers)
      //Use the setField function, which checks whether the field is valid,
      //to set the value.
      return $this->setField('passwordLettersAndNumbers', $passwordLettersAndNumbers);
    

    /**
     * Get whether password must contain upper and lower case characters
     * @return type 
     */
    public function getPasswordUpperLower()
      return $this->passwordUpperLower;
    

    /**
     * Set whether password must contain upper and lower case characters
     * @param type $passwordUpperLower
     * @return \Application\Entity\Config 
     */
    public function setPasswordUpperLower($passwordUpperLower)
      //Use the setField function, which checks whether the field is valid,
      //to set the value.
      return $this->setField('passwordUpperLower', $passwordUpperLower);
    

    /**
     * Get the number of failed logins before user is locked out
     * @return int 
     */
    public function getMaxFailedLogins()
      return $this->maxFailedLogins;
    

    /**
     * Set the number of failed logins before user is locked out
     * @param int $maxFailedLogins
     * @return \Application\Entity\Config 
     */
    public function setMaxFailedLogins($maxFailedLogins)
      //Use the setField function, which checks whether the field is valid,
      //to set the value.
      return $this->setField('maxFailedLogins', $maxFailedLogins);
    

    /**
     * Get the password validity period in days
     * @return int 
     */
    public function getPasswordValidity()
      return $this->passwordValidity;
    

    /**
     * Set the password validity in days
     * @param int $passwordValidity
     * @return \Application\Entity\Config 
     */
    public function setPasswordValidity($passwordValidity)
      //Use the setField function, which checks whether the field is valid,
      //to set the value.
      return $this->setField('passwordValidity', $passwordValidity);
    

    /**
     * Get the number of days prior to expiry that the user starts getting
     * warning messages
     * @return int 
     */
    public function getPasswordExpiryDays()
      return $this->passwordExpiryDays;
    

    /**
     * Get the number of days prior to expiry that the user starts getting
     * warning messages
     * @param int $passwordExpiryDays
     * @return \Application\Entity\Config 
     */
    public function setPasswordExpiryDays($passwordExpiryDays)
      //Use the setField function, which checks whether the field is valid,
      //to set the value.
      return $this->setField('passwordExpiryDays', $passwordExpiryDays);
    

    /**
     * Get the timeout period of the application
     * @return int 
     */
    public function getTimeout()
      return $this->timeout;
    

    /**
     * Get the timeout period of the application
     * @param int $timeout
     * @return \Application\Entity\Config 
     */
    public function setTimeout($timeout)
      //Use the setField function, which checks whether the field is valid,
      //to set the value.
      return $this->setField('timeout', $timeout);
    

    /**
     * Returns a list of validators for each column. These validators are checked
     * in the class' setField method, which is inherited from the Perceptive\Database\Entity class
     * @return array
     */
    public function getValidators()
      //If the validators array hasn't been initialised, initialise it
      if(!isset($this->validators))
        $validators = array(
            'minLengthUserId' => array(
                new I18nValidator\Int(),
                new Validator\GreaterThan(1),
            ),
            'minLengthUserName' => array(
                new I18nValidator\Int(),
                new Validator\GreaterThan(2),
            ),
            'minLengthUserPassword' => array(
                new I18nValidator\Int(),
                new Validator\GreaterThan(3),
            ),
            'daysPasswordReuse' => array(
                new I18nValidator\Int(),
                new Validator\GreaterThan(-1),
            ),
            'passwordLettersAndNumbers' => array(
                new I18nValidator\Int(),
                new Validator\GreaterThan(-1),
                new Validator\LessThan(2),
            ),
            'passwordUpperLower' => array(
                new I18nValidator\Int(),
                new Validator\GreaterThan(-1),
                new Validator\LessThan(2),
            ),
            'maxFailedLogins' => array(
                new I18nValidator\Int(),
                new Validator\GreaterThan(0),
            ),
            'passwordValidity' => array(
                new I18nValidator\Int(),
                new Validator\GreaterThan(1),
            ),
            'passwordExpiryDays' => array(
                new I18nValidator\Int(),
                new Validator\GreaterThan(1),
            ),
            'timeout' => array(
                new I18nValidator\Int(),
                new Validator\GreaterThan(0),
            )
        );
        $this->validators = $validators;
      

      //Return the list of validators
      return $this->validators;
    

    /**
     * @todo: add a lifecyle event which validates before persisting the entity.
     * This way there is no chance of invalid values being saved to the database.
     * This should probably be implemented in the parent class so all entities know
     * to validate.
     */

还有我的控制器,它可以读写实体:

<?php
/**
 * A restful controller that retrieves and updates configuration information
 */
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;

class ConfigController extends AbstractRestfulController

    /**
     * The doctrine EntityManager for use with database operations
     * @var \Doctrine\ORM\EntityManager
     */
    protected $em;

    /**
     * Constructor function manages dependencies
     * @param \Doctrine\ORM\EntityManager $em 
     */
    public function __construct(\Doctrine\ORM\EntityManager $em)
      $this->em = $em;
    

    /**
     * Retrieves the configuration from the database 
     */
    public function getList()
      //locate the doctrine entity manager
      $em = $this->em;

      //there should only ever be one row in the configuration table, so I use findAll
      $config = $em->getRepository("\Application\Entity\Config")->findAll();

      //return a JsonModel to the user. I use my toArray function to convert the doctrine
      //entity into an array - the JsonModel can't handle a doctrine entity itself.
      return new JsonModel(array(
        'data' => $config[0]->toArray(),
      ));
    

    /**
     * Updates the configuration
     */
    public function replaceList($data)
      //locate the doctrine entity manager
      $em = $this->em;

      //there should only ever be one row in the configuration table, so I use findAll
      $config = $em->getRepository("\Application\Entity\Config")->findAll();

      //use the entity's fromArray function to update the data
      $config[0]->fromArray($data);

      //save the entity to the database
      $em->persist($config[0]);
      $em->flush();

      //return a JsonModel to the user. I use my toArray function to convert the doctrine
      //entity into an array - the JsonModel can't handle a doctrine entity itself.
      return new JsonModel(array(
        'data' => $config[0]->toArray(),
      )); 
    

由于字符限制,我无法粘贴到我的单元测试中,但这里是到目前为止我的单元测试的链接:

对于实体: https://github.com/hputus/config-app/blob/master/module/Application/test/ApplicationTest/Entity/ConfigTest.php

对于控制器: https://github.com/hputus/config-app/blob/master/module/Application/test/ApplicationTest/Controller/ConfigControllerTest.php

一些问题:

我在这里做错了什么吗? 在实体测试中,我对许多不同的字段重复相同的测试 - 有没有办法将这种情况最小化?例如,是否需要在整数列上运行一组标准测试? 在控制器中,我试图“模拟”学说的实体管理器,以便更改不会真正保存到数据库中 - 我这样做是否正确? 控制器中还有什么需要我测试的吗?

提前致谢!

【问题讨论】:

【参考方案1】:

虽然您的代码看起来足够可靠,但它存在一些设计疏漏。

首先,Doctrine 建议将实体视为简单、愚蠢的值对象,并声明它们持有的数据始终被假定为有效。

这意味着任何业务逻辑,例如水合、过滤和验证,都应该移到实体之外的单独层。

说到水合,与其自己实现fromArraytoArray 方法,不如使用提供的DoctrineModule\Stdlib\Hydrator\DoctrineObject 水合器,它也可以与Zend\InputFilter 完美融合,来处理过滤和验证。这将使实体测试变得不那么冗长,并且可以说不需要,因为您将单独测试过滤器。

来自 Doctrine 开发人员的另一个重要建议是不要直接在控制器内部注入 ObjectManager。这是出于封装目的:最好将持久层的实现细节隐藏到Controller,并且再次只公开一个中间层。

在你的情况下,所有这一切都可以通过一个由契约设计的ConfigService 类来完成,它只会提供你真正需要的方法(即findAll()persist() 和其他方便的代理),并且会隐藏控制器不严格需要的依赖项,如EntityManager、输入过滤器等。它还将有助于更轻松地模拟。

这样,如果有一天你想在你的持久层做一些改变,你只需要改变你的实体服务如何实现它的契约:考虑添加一个自定义缓存适配器,或者使用 Doctrine 的 ODM 而不是ORM,甚至根本不使用Doctrine。

除此之外,您的单元测试方法看起来不错。

TL;DR

不应在 Doctrine 实体中嵌入业务逻辑。 您应该将水合器与输入过滤器一起使用。 您不应在控制器中注入 EntityManager。 中间层将有助于实现这些变化,同时保留模型和控制器的解耦。

【讨论】:

感谢您非常详细的回答。所以每个实体都只是一个“愚蠢”的字段列表,每个实体都有自己的“服务”类,其中包含水合器(而不是 toArray/fromArray)、验证、getter 和 setter,以及对 EntityManager 的引用?那么控制器只需要与“服务”类交互吗?就单元测试而言,这意味着对实体本身没有测试,而只是对“服务”类进行测试? 是的,基本上在实体中,您只有属性及其访问器方法,可能还有注释元数据,所以不需要太多测试。 关于服务类的问题,你想要多少取决于实体层次结构的复杂程度。对于简单的架构,您可能不需要为每个实体提供服务。 IE。对于由 User 和 Role 实体组成的模型,在没有 User 的情况下您永远不需要 Role,反之亦然,您可能只需要一个处理这两个实体的 UserService,但在更复杂的身份验证机制中,您可能需要更多的灵活性,所以最好用单独的服务来处理它们。最后,这是一个设计决定。 ;)【参考方案2】:

    您的测试看起来与我们的测试非常相似,因此没有任何明显的迹象表明您做错了。 :)

    我同意这“闻起来”有点奇怪,但我对此没有答案。我们的标准是让我们所有的模型“哑”,我们不测试它们。这不是我推荐的,而是因为在我不想只是猜测之前我还没有遇到过你的场景。

    您的测试似乎非常详尽,尽管我真的建议您查看模拟框架:Phake (http://phake.digitalsandwich.com/docs/html/) 将您的断言与模拟分开确实很有帮助,因为并且提供比内置的 phpunit 模拟更易于消化的语法。

    祝你好运!

【讨论】:

如果你的模型很“笨”,你在哪里写你的业务逻辑?如果我可以问。 在此示例中,模型是具有成员变量和 getter/setter 的对象。我们的流程如下:控制器调用 api 包装器(通常从数据库返回代表数据的模型),并将这些模型传递给包含业务逻辑的其他类,他们从业务逻辑类中获取响应,并为查看。

以上是关于Zend Framework 和 Doctrine 2 - 我的单元测试是不是足够?的主要内容,如果未能解决你的问题,请参考以下文章

DQL 语句在使用 Zend Framework 和 Doctrine 的应用程序中的位置

是否可以将 Doctrine 2 与 Zend Framework 1.1x 集成?

Zend Framework 2 + Doctrine 2 [关闭]

PHP 将Zend Framework 1.10与Doctrine 2集成(使用Doctrine的Autoloader)

PHP 将Zend Framework 1.10与Doctrine 2集成

如何避免与 Doctrine2 和 Zend Framework 2 的多对多关系重复?