用PHPUnit测试Symfony UniqueConstraintViolationException的例子

106 阅读1分钟

这个例子告诉我们如何用PHPUnit测试SymfonyUniqueConstraintViolationException 。当持久化一个包含已经在数据库中的数据的实体时,就会出现这种异常--例如,一个电子邮件地址、用户名等等。

你的服务

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

你的服务测试

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