-1

I have some code that persist an object with doctrine, then use its newly generated id to link it to another object.

But when I want to test the code, the id is not generated

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(); 
    }
}

When launching the test I get the following error :

TypeError: Argument 1 passed to ...\Link::setFooId() must be of the type int, null given

Is this a default logic of my code, or the normal behavior of doctrine ?

EDIT :

Finally found the right topic for my question : Symfony2 : Doctrine : PHPUnit : Set entity Id during flushing with mocked entity manager in unit tests

I used his first solution

Kvn91
  • 176
  • 1
  • 10

1 Answers1

-2

Because it is unit test, If you want to get id, you need flush entity, and after that doctrine fill the ID field, but it will be functional test, because you have to use database.

In unit test you dont able to test ID assignment, it is possible only in functional test