使用Doctrine DataFixtures用PHPUnit测试Symfony存储库的例子

88 阅读1分钟

在这个例子中,我们要测试Symfony资源库,看看我们是否能正确地从数据库中获得数据。数据库中的数据是由Doctrine DataFixtures填充的。

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

测试

$ 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)