This example shows us how to test Symfony UniqueConstraintViolationException with PHPUnit. This exception occurs when persisting an entity that contains a data that is already in database - e.g. An email address, username so on.


YourService


use App\Entity\YourEntity;
use App\Exception\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');
}
}
}

YourServiceTest


use App\Entity\YourEntity;
use App\Exception\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);
}
}