LoginSignup
0

posted at

【PHPUnit】テストデータ作成時はFakerを積極的に使おう

環境

Laravel v9.5.1 (PHP v8.1.3)

テストデータを作成するとき

テストケースではパラメーターに入れる値などを直接入れないほうがいいらしい。
値を固定してしまうと本当の意味で正確なテストではなくなってしまう。

Bad

$this->users = User::factory(2)->create();
$params = [
      'user_id' => $this->users[0]->id,
      'message' => 'メッセージです',
      'points' => 10,
];

Good

Fakerなどを使うとテストが実行されるごとにランダムな値でテストしてくれる。

$this->users = User::factory(2)->create();
$params = [
      'user_id' => $this->users[0]->id,
      'message' => Str::random(10),
      'points' => Faker\Factory::create()->randomDigit,
];

メールドメインもある。とにかくなんでもある。

$this->faker->unique()->safeEmailDomain()

Railsをメインでやっていたとき、RSpecではFakerを使ったことがなかったので存在を知らなかったけどめっちゃ便利…!

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0