持久化新对象并生成其 id 的单元测试代码

问题描述

我有一些代码一个带有学说的对象持久化,然后使用其新生成的 id 将其链接到另一个对象。

但是当我想测试代码时,没有生成id

class Foo extends DefaultDocument
{

    /**
     * @var int
     * @MongoDB\Field(type="int")
     * @MongoDB\Id(strategy="INCREMENT")
     */
     protected $id
}


class Link
{
    /**
     * @var int
     * @MongoDB\Field(type="int")
     */
    private $fooId;
}


class Service
{

    public function doesSomething()
    {
        $foo = new Foo();
        $this->documentManager->persist($foo);

        $link = new Link();
        $link->setFooId($foo->getId());
    }
}


class TestService
{
    private function createService()
    {
        return new Service();
    }

    public function testDoesSomething()
    {
        $service = $this->createService();
        $service->doesSomething(); 
    }
}

启动测试时出现以下错误

TypeError:传递给 ...\Link::setFooId() 的参数 1 必须属于 输入 int,给定 null

这是我代码认逻辑,还是教义的正常行为?

编辑:

终于为我的问题找到了正确的话题: Symfony2 : Doctrine : PHPUnit : Set entity Id during flushing with mocked entity manager in unit tests

我使用了他的第一个解决方

解决方法

因为是单元测试,如果要获取id,需要flush entity,然后再填充id字段,但是会是功能测试,因为要使用数据库。

在单元测试中不能测试 ID 分配,只能在功能测试中进行