LoginSignup
1
0

More than 1 year has passed since last update.

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

Posted at

環境

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を使ったことがなかったので存在を知らなかったけどめっちゃ便利…!

1
0
0

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
  3. You can use dark theme
What you can do with signing up
1
0