How to create tests w/Doctrine entities without persisting them (how to set id)

前端 未结 3 485
孤街浪徒
孤街浪徒 2021-02-04 08:41

I\'m working on tests for a Symfony2 project, and right now I\'m looking for a way to create tests involving entity objects without persisting them. The problem is: id

相关标签:
3条回答
  • 2021-02-04 09:30

    You can configure doctrine to use an in-memory database in your app/config/config_test.yml.

    # app/config/config_test
    doctrine:
        dbal:
            driver: pdo_sqlite
            path: :memory:
            memory: true
    

    This speeds up the process and you can quickly persist some fixtures in the setUp() method that will have (auto-generated) id's after flushing... all without messing with your "real" database.

    You can find some inspiration in this answer and this blog post.

    0 讨论(0)
  • 2021-02-04 09:40

    Another way is to create a child of your entity (this could live in the tests folder if you want to keep things clean), then add the "setId()" method to the child

    class TestableEntity extends \My\Namespace\Entity
    {
        public function setId($id)
        {
           $this->id = $id;
    
           return $this;
        }
    }
    

    Your tests should then test the TestableEntity, rather than the real entity. As long as the "id" property in \My\Namespace\Entity is protected, rather than private, it can be set via the TestableEntity.

    0 讨论(0)
  • 2021-02-04 09:44

    It's little bit old but it's worthy to say that maybe the best way is to have helper method that is using Reflection to alter those protected values.

    Example :

    public function set($entity, $value, $propertyName = 'id')
    {
        $class = new ReflectionClass($entity);
        $property = $class->getProperty($propertyName);
        $property->setAccessible(true);
    
        $property->setValue($entity, $value);
    }
    

    put that in base test class that you extends or have it in trait and just use it when you need something like that in test. In that way you will be able to write tests without having to create dirty changes.

    0 讨论(0)
提交回复
热议问题