首页 > 解决方案 > 持久化新对象并生成其 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

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

标签: unit-testingsymfonytestingdoctrinedoctrine-odm

解决方案


因为是单元测试,如果要获取id,就需要flush entity,然后学说填id字段,不过是功能测试,因为要使用数据库。

在单元测试中,您无法测试 ID 分配,只有在功能测试中才有可能


推荐阅读