Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

In this example we are going to test Symfony repository to see if we get data from database correctly. The data in database is populated with Doctrine DataFixtures.


CountryRepository


declare(strict_types=1);

namespace App\Repository;

use Doctrine\ORM\EntityRepository;

class CountryRepository implements CountryRepositoryInterface
{
private $entityRepository;

public function __construct(
EntityRepository $entityRepository
) {
$this->entityRepository = $entityRepository;
}

public function findAll(): iterable
{
return $this->entityRepository
->createQueryBuilder('c')
->getQuery()
->getArrayResult();
}
}

CountryRepositoryTest


declare(strict_types=1);

namespace App\Tests\Repository;

use App\Entity\Country;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class CountryRepositoryTest extends KernelTestCase
{
/** @var EntityManagerInterface */
private $entityManager;

protected function setUp()
{
$kernel = self::bootKernel();

$this->entityManager = $kernel->getContainer()
->get('doctrine')
->getManager();
}

protected function tearDown()
{
parent::tearDown();

$this->entityManager->close();
$this->entityManager = null;
}

/**
* @test
* @dataProvider getCountriesDataProvider
*/
public function find_all_returns_all_records(int $id, string $code, string $name): void
{
$countries = $this->entityManager
->getRepository(Country::class)
->findAll();

$this->assertCount(3, $countries);
$this->assertSame($id, $countries[$id-1]->getId());
$this->assertSame($code, $countries[$id-1]->getCode());
$this->assertSame($name, $countries[$id-1]->getName());
}

public function getCountriesDataProvider(): iterable
{
return [
[
'$id' => 1,
'$code' => 'gb',
'$name' => 'Great Britain',
],
[
'$id' => 2,
'$code' => 'tr',
'$name' => 'Turkey',
],
[
'$id' => 3,
'$code' => 'de',
'$name' => 'Germany',
],
];
}
}

Test


$ vendor/bin/phpunit --filter CountryRepositoryTest tests/Repository/CountryRepositoryTest.php 
PHPUnit 7.1.5 by Sebastian Bergmann and contributors.

... 3 / 3 (100%)

Time: 223 ms, Memory: 10.00MB

OK (3 tests, 12 assertions)