composer remove phpunit/phpunit
composer require pestphp/pest --dev --with-all-dependencies
./vendor/bin/pest --init
./vendor/bin/pest
.bash_profile Aliasを設定しておきましょう。
alias pest='./vendor/bin/pest'
pest --filter="ユーザー作成に成功する"
cp .env .env.testing
.env.testing
# テスト用インメモリ Sqlite
DB_CONNECTION=sqlite
DB_DATABASE=:memory:
phpunit.xml
<php>
<env name="APP_ENV" value="testing"/>
</php>
./vendor/bin/pest
tests/Feature/ExampleModelTest.php
<?php
use App\Models\Post;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
test('postsテーブルにデータを1件追加できる', function () {
// 初期状態でpostsテーブルが空であることを確認
expect(Post::count())->toBe(0);
// データを追加
$post = Post::create([
"name" => "テストタイトル",
"content_name" => "テストデータ",
]);
// データベースに1件追加されたことを確認
expect(Post::count())->toBe(1);
// 追加されたデータが存在することを確認
$this->assertDatabaseHas('posts', [
'id' => $post->id,
]);
});
beforeEach(function () {
// データベース接続情報を表示
$connection = DB::connection();
dump([
'===== データベース接続情報 =====' => '',
'ドライバー' => $connection->getDriverName(),
'データベース名' => $connection->getDatabaseName(),
'ホスト' => $connection->getConfig('host'),
'ポート' => $connection->getConfig('port'),
'接続名' => $connection->getName(),
'環境変数 DB_CONNECTION' => env('DB_CONNECTION'),
'環境変数 DB_DATABASE' => env('DB_DATABASE'),
'環境変数 APP_ENV' => env('APP_ENV'),
'================================' => '',
]);
});
./vendor/bin/pest
APP_URL=http://localhost/hogehoge
の場合
EndpointTest.php
<?php
describe('GET /hello', function () {
test('正常系: /hello エンドポイントが正常に動作する', function () {
$response = $this->get('/hello');
$response->assertStatus(200);
});
});
なので、.env.testing では
# ===== テスト用URL(テスト用にサブディレクトリは含まないように記述すること。 ) =====
APP_URL=http://localhost
# ===== /テスト用URL =====
する必要があります 。