Bu örnekte veriyi doğru bir şekilde veritabanından aldığımızı görmek için Symfony repositorilerini test edeceğiz. Veritabanındaki veriler Doctrine DataFixtures ile doldurulur.


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)