Skip to content

Commit 8182c7b

Browse files
committed
[Uid] Add documentation for MockUuidFactory usage in tests
1 parent 32ee550 commit 8182c7b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

components/uid.rst

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,65 @@ of the UUID parameters::
433433
}
434434
}
435435

436+
MockUuidFactory
437+
===============
438+
439+
.. versionadded:: 7.4
440+
The :class:`Symfony\Component\Uid\Factory\MockUuidFactory` class was introduced in Symfony 7.4.
441+
442+
The :class:`Symfony\Component\Uid\Factory\MockUuidFactory` class allows you to control the UUIDs generated during your tests, making them predictable and reproducible.
443+
444+
Suppose you have a service that generates a UUID for each new user:
445+
446+
.. code-block:: php
447+
448+
use Symfony\Component\Uid\Factory\UuidFactory;
449+
use Symfony\Component\Uid\Uuid;
450+
451+
class UserService
452+
{
453+
public function __construct(private UuidFactory $uuidFactory) {}
454+
455+
public function createUserId(): string
456+
{
457+
return $this->uuidFactory->create()->toRfc4122();
458+
}
459+
}
460+
461+
In your tests, you can use ``MockUuidFactory`` to inject predictable UUIDs and verify the expected behavior:
462+
463+
.. code-block:: php
464+
465+
use PHPUnit\Framework\TestCase;
466+
use Symfony\Component\Uid\Factory\MockUuidFactory;
467+
use Symfony\Component\Uid\UuidV4;
468+
469+
class UserServiceTest extends TestCase
470+
{
471+
public function testCreateUserIdReturnsExpectedUuid()
472+
{
473+
$uuids = [
474+
UuidV4::fromString('11111111-1111-4111-8111-111111111111'),
475+
UuidV4::fromString('22222222-2222-4222-8222-222222222222'),
476+
];
477+
$factory = new MockUuidFactory($uuids);
478+
$service = new UserService($factory);
479+
480+
$this->assertSame('11111111-1111-4111-8111-111111111111', $service->createUserId());
481+
$this->assertSame('22222222-2222-4222-8222-222222222222', $service->createUserId());
482+
}
483+
}
484+
485+
.. warning::
486+
487+
``MockUuidFactory`` is intended for use in tests only and should never be used in production.
488+
489+
.. note::
490+
491+
- Supports the :method:`Symfony\\Component\\Uid\\Factory\\MockUuidFactory::create`, :method:`Symfony\\Component\\Uid\\Factory\\MockUuidFactory::randomBased`, :method:`Symfony\\Component\\Uid\\Factory\\MockUuidFactory::timeBased`, and :method:`Symfony\\Component\\Uid\\Factory\\MockUuidFactory::nameBased` methods.
492+
- You can mix different UUID versions in the same sequence.
493+
- Throws an exception if the sequence is exhausted or the type does not match.
494+
436495
.. _ulid:
437496

438497
ULIDs

0 commit comments

Comments
 (0)