Skip to content

Commit 910426a

Browse files
committed
Merge remote-tracking branch 'upstream/8.0' into 8.0
* upstream/8.0: [Uid] Add documentation for MockUuidFactory usage in tests
2 parents 0e6c6ab + 2afb6a2 commit 910426a

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

components/uid.rst

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,66 @@ of the UUID parameters::
420420
}
421421
}
422422

423+
MockUuidFactory
424+
===============
425+
426+
.. versionadded:: 7.4
427+
428+
The :class:`Symfony\\Component\\Uid\\Factory\\MockUuidFactory` class was introduced in Symfony 7.4.
429+
430+
The :class:`Symfony\\Component\\Uid\\Factory\\MockUuidFactory` class allows you to
431+
control the UUIDs generated during your tests, making them predictable and reproducible.
432+
433+
Suppose you have a service that generates a UUID for each new user::
434+
435+
use Symfony\Component\Uid\Factory\UuidFactory;
436+
use Symfony\Component\Uid\Uuid;
437+
438+
class UserService
439+
{
440+
public function __construct(
441+
private UuidFactory $uuidFactory
442+
){
443+
}
444+
445+
public function createUserId(): string
446+
{
447+
return $this->uuidFactory->create()->toRfc4122();
448+
}
449+
}
450+
451+
In your tests, you can use ``MockUuidFactory`` to inject predictable UUIDs and verify the expected behavior::
452+
453+
use PHPUnit\Framework\TestCase;
454+
use Symfony\Component\Uid\Factory\MockUuidFactory;
455+
use Symfony\Component\Uid\UuidV4;
456+
457+
class UserServiceTest extends TestCase
458+
{
459+
public function testCreateUserIdReturnsExpectedUuid()
460+
{
461+
$factory = new MockUuidFactory([
462+
UuidV4::fromString('11111111-1111-4111-8111-111111111111'),
463+
UuidV4::fromString('22222222-2222-4222-8222-222222222222'),
464+
]);
465+
466+
$service = new UserService($factory);
467+
468+
$this->assertSame('11111111-1111-4111-8111-111111111111', $service->createUserId());
469+
$this->assertSame('22222222-2222-4222-8222-222222222222', $service->createUserId());
470+
}
471+
}
472+
473+
.. warning::
474+
475+
``MockUuidFactory`` is intended for use in tests only and should never be used in production.
476+
477+
.. note::
478+
479+
- 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.
480+
- You can mix different UUID versions in the same sequence.
481+
- Throws an exception if the sequence is exhausted or the type does not match.
482+
423483
.. _ulid:
424484

425485
ULIDs

0 commit comments

Comments
 (0)