[Laravel] 6장 라라벨 테스트 및 디버깅

1. PHPUnit 설치 및 설정

Laravel은 기본적으로 PHPUnit이 설치되어 있어, phpunit.xml 파일이 프로젝트 루트에 위치하고 있습니다. 이 파일은 PHPUnit의 설정을 포함하고 있습니다. 만약 PHPUnit이 설치되어 있지 않다면 아래 Composer로 설치합니다.

composer require --dev phpunit/phpunit

2. 테스트 작성

Laravel에서는 다양한 유형의 텍스트를 작성할 수 있습니다. 여기서 기본적인 유닛 테스트와 기능 테스트를 작성할 수 있습니다. 먼저 Artisan CLI를 사용하여 새로운 테스트 클래스를 생성합니다.

php artisan make:test ExampleTest --unit

 

위 명령어로 생성된 tests/Unit/ExampleTest.php 파일을 열고 테스트 메서드를 작성합니다.

// tests/Unit/ExampleTest.php
<?php 
  namespace Tests\Unit;

 use PHPUnit\Framework\TestCase;

 class ExampleTest extends TestCase 
 {
    public function testBasicTest()
    {
        $this->assertTrue(true); // Default Text
    }
 }
?>

3. 기능 테스트

이제 기능을 테스트하기 위해 기능 테스트를 생성합니다. 아래 명령어로 ExampleFeatureTest를 생성합니다.

php artisan make:test ExampleFeatureTest

 

생성된 tests/Feature/ExampleFeatureTest.php 파일을 열고 기능 테스트 메서드를 작성합니다.

// tests/Feature/ExampleFeatureTest.php
<?php

namespace Tests\Feature;

 
use Tests\TestCase;

class ExampleFeatureTest extends TestCase
{
    public function testHomePage()
    {
        $response = $this->get('/'); // HomePage request
        $response->assertStatus(200); // Request State 
        $response->assertSee("Welcome"); // Page detail 
    }
}

 

테스트를 실행하기 위해 터미널에서 다음 명령어로 테스트를 실행합니다.

php artisan test

4. 디버깅 기술 습득

Laravle에서는 여러 가지 디버깅 도구를 사용할 수 있고, 대표적으로 Laravel Debugbar과 dd() 함수가 있습니다. 먼저 Laravel Debugger를 설치하려면 아래와 같은 명령어로 설치합니다.

composer require barryvdh/laravel-debugbar --dev

 

Debugger를 설치한 후에 .env 파일에서 다음을 추가해 활성화해줍니다.

DEBUGBAR_ENABLED=true

 

먼저 프로젝트 루트 디렉토리로 이동한 후, 개발 서버를 실행합니다. 그럼 페이지 하단에 Debugbar이 나타납니다. 쿼리, 요청 시간, 메모리 사용량 등을 확인할 수 있습니다.

php artisan serve

 

원하는 컨트롤러 파일을 열고, dd() 또는 dump() 함수를 사용해 디버깅하려는 부분에 코드를 추가합니다.

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::all(); // 모든 게시물 가져오기 
        dd($posts->toArray()); // dd()로 데이터 확인 이 부분에서 실행 중단 후 데이터 출력
        
        // 모든 게시글과 각 게시글의 댓글 
        $posts = Post::with('comments')->get();
        

        // 또는 Log::Info()로 로그 남기기
        Log::info("Posts retrieved", $posts->toArray());
        return view('posts.index', compact('posts'));
    }

5. 웹 라우트 설정

routes/web.php파일에서 Post 컨트롤러의 라우트를 설정합니다.

use App\Http\Controllers\PostController;

// Post Comment Route
Route::get('/posts', [PostController::class, 'index']);

 

이제 웹 브라우저를 열고 http://127.0.0.1.8000/posts로 이동하면 dd() 함수가 호출되며, 모든 게시물이 출력되고 페이지가 중단됩니다. Log::info()를 사용하면 laravel.log 파일(storage/logs/laravle.log)을 열어 로그 메시지를 확인합니다.


 

GitHub - Koras02/laravel-bloging

Contribute to Koras02/laravel-bloging development by creating an account on GitHub.

github.com

 

LIST