Skip to content
Advertisement

Symfony mocking repository for testing

I’m trying to mock a repository containing all modules, and it has a method called findAll() that returns all elements from that repository. I cant seem to be able to pull any data from the mocked repository. Any ideas how I could fix it?

Mocking repository:

JavaScript

Trying to use method from ModuleRepository class called findAll() that returns all elements from the repo in an array.

JavaScript

Thats what I get when I print $moduleRepository:

JavaScript

I tried it like this and the method actually gets called, but the repo has no data for it to find.

JavaScript

Output:

JavaScript

Advertisement

Answer

Your moduleRepository will always return empty array, because you said to do it.

here you said to return an empty array []:

JavaScript

from method findAll:

JavaScript

There are some ways how to handle it, but for now, I recommend you to create a new database only for testing purposes, then create a new .env.test file which will extend the original .env file and use the exact repository instead of mock.

JavaScript
JavaScript

Be sure you will fill up a new database with the data. It’s a good idea to create fixtures for doing it automatically and clean up the database on tearDown method.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement