zenstruck / foundry

A model factory library for creating expressive, auto-completable, on-demand dev/test fixtures with Symfony and Doctrine.
https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html
MIT License
608 stars 63 forks source link

How to get the EntityManager used by foundry? #566

Closed janopae closed 4 months ago

janopae commented 4 months ago

Using foundry, I can call repository(MyClass::class) to get a repository operating on the EntityManager that foundry uses. However, this method only gives me access to an object of type ObjectRepository<MyClass>.

Sometimes, however, you need access to your specific implementation of the repository in tests. That's easy, you just create your repository like new MyClassRepository($entityManager) with the EntityManager in operation in your test case.

But how to get this EntityManager using Foundry?

janopae commented 4 months ago

I just realised that in a KernelTestCase, you can call self::getContainer()->get(EntityManagerInterface::class). However, this is not the logic used inside the repository($class) function – that function uses the @internal Configuration class, which selects the right EntityMaanger from a ManagerRegistry, which is private. This might differ in some edge cases?

nikophil commented 4 months ago

Hi @janopae

why don't you grab the repository with self::getContainer()->get(MyShinyRepository::class)?

janopae commented 4 months ago

You are right, this should use the same EntityManager, as the Factory will use the EntityManager as the Service configuration.

I'm migrating from a different database testing library that doesn't boot a whole Symfony kernel, so I forgot that I can just use the KernelTestCase functionality.

Thanks for your reply!