26/02/2019 - PHPUNIT, SYMFONY
Bu örnek, Symfony UniqueConstraintViolationException
'ın PHPUnit ile nasıl test edileceğini gösterir. Bu exception, daha önceden veritabanında bulunan veriyi tekrardan kaydetmeye çalıştığımızda oluşur. Örnek: Email adres, username vs.
use App\Entity\YourEntity;
use App\Entity\YourBadRequestException;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
class YourService
{
public function handle(YourEntity $entity): void
{
try {
$repo->persist($entity);
} catch (UniqueConstraintViolationException $e) {
throw new YourBadRequestException('Ouuuu');
}
}
}
use App\Entity\YourEntity;
use App\Entity\YourBadRequestException;
use Doctrine\DBAL\Driver\AbstractDriverException;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
class YourServiceTest extends TestCase
{
public function testUniqueConstraintViolation(): void
{
$entity = (new YourEntity())->setUsername('hello');
$repoMock = $this->createMock(YourRepository::class);
$driverExceptionMock = $this->createMock(AbstractDriverException::class);
$repoMock
->expects($this->once())
->method('persist')
->with($entity)
->willThrowException(new UniqueConstraintViolationException('The original error.', $driverExceptionMock));
$this->expectException(YourBadRequestException::class);
$this->expectExceptionMessage('Ouuuu.');
$this->expectExceptionCode(Response::HTTP_BAD_REQUEST);
$yourService = new YourService();
$yourService->handle($entity);
}
}