はじめに
こんばんは。
ちょっとまえに、laravelの uuid()
を使用しているコードのテストを行う必要があったので、対応してみました。
簡単ですが備忘録です。
本題
uuid()のコード自体は Illuminate\Support\Str::uuid()
を使ってます。
/** * Generate a UUID (version 4). * * @return \Ramsey\Uuid\UuidInterface */ public static function uuid() { return static::$uuidFactory ? call_user_func(static::$uuidFactory) : Uuid::uuid4(); }
UuidFactoryInterfaceをimplementsした無名クラスとかでも良さそうなんですが、mockでテストのときに固定値を返すようにするほうが楽そう?なのでやってみました。
namespace Tests\Unit; use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidFactory; use Ramsey\Uuid\UuidFactoryInterface; use Tests\TestCase; class ExampleTest extends TestCase { protected function setUp(): void { parent::setUp(); /** @var UuidFactoryInterface $factory */ $factory = $this->mock( UuidFactoryInterface::class, static fn ($mock) => $mock->shouldReceive('uuid4')->andReturn( Uuid::fromString('99999999-9999-9999-9999-999999999999') ) ); Uuid::setFactory($factory); } protected function tearDown(): void { parent::tearDown(); Uuid::setFactory(new UuidFactory()); } public function test_invoke(): void { dd(Uuid::uuid4()->toString()); // "99999999-9999-9999-9999-999999999999" } }
終わりに
こんな感じで上書きできました。
Illuminate\Support\Str
をmockするのでもよさそうでしたねw
簡単ですが以上です。