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.

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);
}
}