Logan Bailey

Adventures In Web Development

Blog, About, GitHub, and LinkedIn

Generating Uuids with Ramsey Uuid is damn easy, \Ramsey\Uuid\Uuid::uuid1(). Generating predictable Uuids for testing can be easy to. The library exposes a method, setFactory, that allows the developer to change the class used to generate Uuid. In my parent testCase, I add the following functions:

/**
 * Sets the expected responses from `Uuid::uuid1()`.
 *
 * If you're using this method, make sure to call `clearUuid()` in tearDown.
 *
 * @param string[] $uuids An array of string representations of Uuids
 */
protected function setUuid1Values(array $uuids)
{
    $stack = array_map(function ($uuid) {
        return \Ramsey\Uuid\Uuid::fromString($uuid);
    }, $uuids);

    $factory = $this->createMock(\Ramsey\Uuid\UuidFactoryInterface::class);
    $factory
        ->expects($this->exactly(count($revs)))
        ->method('uuid1')
        ->will(new \PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls($stack));

    \Ramsey\Uuid\Uuid::setFactory($factory);
}

protected function clearUuid()
{
    \Ramsey\Uuid\Uuid::setFactory(new \Ramsey\Uuid\UuidFactory());
}

This can be used in your test as follows:

public function testUuidMocking()
{
    $this->setUuid1Values([
        'e36f227c-2946-11e8-b467-0ed5f89f718b',
        'd71187bc-2947-11e8-b467-0ed5f89f718b'
    ]);

    \Ramsey\Uuid\Uuid::uuid1()->toString(); // e36f227c-2946-11e8-b467-0ed5f89f718b
    \Ramsey\Uuid\Uuid::uuid1()->toString(); // d71187bc-2947-11e8-b467-0ed5f89f718b
}

The setUuid1Values method verifies number of v1 uuids that are generated and sets the specific results from each consecutive call. This method can be modified to mock the generation of other uuid versions depending on your use case.

Posted In:
php phpunit uuid