HTTP 테스트
번역일: 2026년 6월 21일
HTTP 테스트
소개
Laravel은 애플리케이션에 HTTP 요청을 보내고 응답을 검증하기 위한 유연한 API를 제공합니다. 아래의 기능 테스트 예시를 살펴보겠습니다.
Pest
<?php
test('애플리케이션이 정상 응답을 반환한다', function () {
$response = $this->get('/');
$response->assertStatus(200);
});PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* 기본 테스트 예시
*/
public function test_the_application_returns_a_successful_response(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}get 메서드는 애플리케이션에 GET 요청을 보내고, assertStatus 메서드는 반환된 응답이 지정한 HTTP 상태 코드를 가지는지 검증합니다. 이 외에도 Laravel은 응답 헤더, 본문, JSON 구조 등을 검사하는 다양한 assertion 메서드를 제공합니다.
요청 만들기
테스트에서 get, post, put, patch, delete 메서드를 사용해 애플리케이션에 요청을 보낼 수 있습니다. 이 메서드들은 실제 네트워크 HTTP 요청을 보내는 것이 아니라, 내부적으로 요청을 시뮬레이션합니다.
이 메서드들은 Illuminate\Http\Response 인스턴스 대신, 다양한 assertion 메서드를 제공하는 Illuminate\Testing\TestResponse 인스턴스를 반환합니다.
Pest
<?php
test('기본 요청', function () {
$response = $this->get('/');
$response->assertStatus(200);
});PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* 기본 테스트 예시
*/
public function test_a_basic_request(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}일반적으로 하나의 테스트 메서드 안에서는 요청을 한 번만 보내는 것이 좋습니다. 단일 테스트 메서드에서 여러 요청을 실행하면 예기치 않은 동작이 발생할 수 있습니다.
NOTE
테스트 실행 시 CSRF 미들웨어는 자동으로 비활성화됩니다.
요청 헤더 커스터마이징
withHeaders 메서드를 사용하면 요청을 보내기 전에 헤더를 원하는 대로 설정할 수 있습니다.
Pest
<?php
test('헤더와 상호작용', function () {
$response = $this->withHeaders([
'X-Header' => 'Value',
])->post('/user', ['name' => '홍길동']);
$response->assertStatus(201);
});PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* 헤더 커스터마이징 테스트 예시
*/
public function test_interacting_with_headers(): void
{
$response = $this->withHeaders([
'X-Header' => 'Value',
])->post('/user', ['name' => '홍길동']);
$response->assertStatus(201);
}
}쿠키
withCookie 또는 withCookies 메서드를 사용하면 요청 전에 쿠키 값을 설정할 수 있습니다. withCookie는 쿠키 이름과 값을 인수로 받고, withCookies는 이름/값 쌍의 배열을 받습니다.
Pest
<?php
test('쿠키와 상호작용', function () {
$response = $this->withCookie('color', 'blue')->get('/');
$response = $this->withCookies([
'color' => 'blue',
'name' => 'Taylor',
])->get('/');
//
});PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_interacting_with_cookies(): void
{
$response = $this->withCookie('color', 'blue')->get('/');
$response = $this->withCookies([
'color' => 'blue',
'name' => 'Taylor',
])->get('/');
//
}
}세션 / 인증
Laravel은 HTTP 테스트 중 세션과 상호작용하기 위한 여러 헬퍼를 제공합니다. withSession 메서드를 사용하면 요청을 보내기 전에 세션 데이터를 미리 설정할 수 있습니다.
Pest
<?php
test('세션과 상호작용', function () {
$response = $this->withSession(['banned' => false])->get('/');
//
});PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_interacting_with_the_session(): void
{
$response = $this->withSession(['banned' => false])->get('/');
//
}
}세션은 주로 인증된 사용자의 상태를 유지하는 데 사용됩니다. actingAs 헬퍼 메서드를 사용하면 특정 사용자를 현재 인증된 사용자로 간편하게 지정할 수 있습니다. 예를 들어, 모델 팩토리를 사용하여 사용자를 생성하고 인증할 수 있습니다.
Pest
<?php
use App\Models\User;
test('인증이 필요한 동작', function () {
$user = User::factory()->create();
$response = $this->actingAs($user)
->withSession(['banned' => false])
->get('/');
//
});PHPUnit
<?php
namespace Tests\Feature;
use App\Models\User;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_an_action_that_requires_authentication(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)
->withSession(['banned' => false])
->get('/');
//
}
}actingAs 메서드의 두 번째 인수로 가드 이름을 전달하여 인증에 사용할 가드를 지정할 수도 있습니다. 지정된 가드는 해당 테스트가 실행되는 동안 기본 가드로 사용됩니다.
$this->actingAs($user, 'web');요청을 비인증 상태로 보내고 싶다면 actingAsGuest 메서드를 사용하세요.
$this->actingAsGuest();응답 디버깅
테스트 요청을 보낸 후 dump, dumpHeaders, dumpSession 메서드를 사용하여 응답 내용을 확인하고 디버깅할 수 있습니다.
Pest
<?php
test('기본 테스트', function () {
$response = $this->get('/');
$response->dump();
$response->dumpHeaders();
$response->dumpSession();
});PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* 기본 테스트 예시
*/
public function test_basic_test(): void
{
$response = $this->get('/');
$response->dump();
$response->dumpHeaders();
$response->dumpSession();
}
}응답 정보를 출력하고 즉시 실행을 중단하고 싶다면 dd, ddHeaders, ddBody, ddJson, ddSession 메서드를 사용하세요.
Pest
<?php
test('기본 테스트', function () {
$response = $this->get('/');
$response->dd();
$response->ddHeaders();
$response->ddBody();
$response->ddJson();
$response->ddSession();
});PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* 기본 테스트 예시
*/
public function test_basic_test(): void
{
$response = $this->get('/');
$response->dd();
$response->ddHeaders();
$response->ddBody();
$response->ddJson();
$response->ddSession();
}
}예외 처리
특정 예외가 발생하는지 테스트해야 할 때가 있습니다. 이를 위해 Exceptions 파사드를 사용해 예외 핸들러를 페이크로 대체할 수 있습니다. 예외 핸들러를 페이크로 만든 후, assertReported와 assertNotReported 메서드를 사용해 요청 중에 발생한 예외를 검증할 수 있습니다.
Pest
<?php
use App\Exceptions\InvalidOrderException;
use Illuminate\Support\Facades\Exceptions;
test('예외가 발생한다', function () {
Exceptions::fake();
$response = $this->get('/order/1');
// 예외가 발생했는지 검증
Exceptions::assertReported(InvalidOrderException::class);
// 예외 내용을 검증
Exceptions::assertReported(function (InvalidOrderException $e) {
return $e->getMessage() === '주문이 유효하지 않습니다.';
});
});PHPUnit
<?php
namespace Tests\Feature;
use App\Exceptions\InvalidOrderException;
use Illuminate\Support\Facades\Exceptions;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* 기본 테스트 예시
*/
public function test_exception_is_thrown(): void
{
Exceptions::fake();
$response = $this->get('/order/1');
// 예외가 발생했는지 검증
Exceptions::assertReported(InvalidOrderException::class);
// 예외 내용을 검증
Exceptions::assertReported(function (InvalidOrderException $e) {
return $e->getMessage() === '주문이 유효하지 않습니다.';
});
}
}assertNotReported와 assertNothingReported 메서드를 사용하면 특정 예외가 발생하지 않았거나 아무 예외도 발생하지 않았음을 검증할 수 있습니다.
Exceptions::assertNotReported(InvalidOrderException::class);
Exceptions::assertNothingReported();요청에 대해 예외 처리를 완전히 비활성화하려면 요청 전에 withoutExceptionHandling 메서드를 호출하세요.
$response = $this->withoutExceptionHandling()->get('/');PHP 언어나 사용 중인 라이브러리에서 더 이상 사용되지 않는(deprecated) 기능을 애플리케이션이 사용하고 있는지 확인하려면 withoutDeprecationHandling 메서드를 요청 전에 호출하세요. 이 메서드를 사용하면 deprecation 경고가 예외로 변환되어 테스트가 실패하게 됩니다.
$response = $this->withoutDeprecationHandling()->get('/');assertThrows 메서드는 클로저 내 코드가 지정한 타입의 예외를 발생시키는지 검증합니다.
$this->assertThrows(
fn () => (new ProcessOrder)->execute(),
OrderInvalid::class
);발생한 예외를 직접 검사하고 싶다면 두 번째 인수로 클로저를 전달할 수 있습니다.
$this->assertThrows(
fn () => (new ProcessOrder)->execute(),
fn (OrderInvalid $e) => $e->orderId() === 123;
);assertDoesntThrow 메서드는 클로저 내 코드가 예외를 발생시키지 않는지 검증합니다.
$this->assertDoesntThrow(fn () => (new ProcessOrder)->execute());JSON API 테스트
Laravel은 JSON API 및 응답을 테스트하기 위한 다양한 헬퍼를 제공합니다. json, getJson, postJson, putJson, patchJson, deleteJson, optionsJson 메서드를 사용하면 다양한 HTTP 메서드로 JSON 요청을 보낼 수 있습니다. 데이터와 헤더도 쉽게 전달할 수 있습니다. 아래 예시는 /api/user에 POST 요청을 보내고 반환된 JSON을 검증합니다.
Pest
<?php
test('API 요청 보내기', function () {
$response = $this->postJson('/api/user', ['name' => '홍길동']);
$response
->assertStatus(201)
->assertJson([
'created' => true,
]);
});PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* 기본 기능 테스트 예시
*/
public function test_making_an_api_request(): void
{
$response = $this->postJson('/api/user', ['name' => '홍길동']);
$response
->assertStatus(201)
->assertJson([
'created' => true,
]);
}
}JSON 응답 데이터는 배열처럼 응답 객체에서 직접 접근할 수 있어 개별 값을 편리하게 확인할 수 있습니다.
Pest
expect($response['created'])->toBeTrue();PHPUnit
$this->assertTrue($response['created']);NOTE
assertJson 메서드는 응답을 배열로 변환하여 지정한 배열이 JSON 응답 안에 존재하는지 확인합니다. JSON 응답에 다른 속성이 있더라도 지정한 데이터가 포함되어 있으면 테스트는 통과합니다.
정확한 JSON 일치 검증
assertJson은 지정한 데이터가 응답에 포함되어 있는지만 확인합니다. 반환된 JSON과 정확히 일치하는지 검증하려면 assertExactJson 메서드를 사용하세요.
Pest
<?php
test('정확한 JSON 일치 검증', function () {
$response = $this->postJson('/user', ['name' => '홍길동']);
$response
->assertStatus(201)
->assertExactJson([
'created' => true,
]);
});PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* 기본 기능 테스트 예시
*/
public function test_asserting_an_exact_json_match(): void
{
$response = $this->postJson('/user', ['name' => '홍길동']);
$response
->assertStatus(201)
->assertExactJson([
'created' => true,
]);
}
}JSON 경로 값 검증
특정 경로의 JSON 데이터를 검증하려면 assertJsonPath 메서드를 사용하세요.
Pest
<?php
test('JSON 경로 값 검증', function () {
$response = $this->postJson('/user', ['name' => '홍길동']);
$response
->assertStatus(201)
->assertJsonPath('team.owner.name', '김철수');
});PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* 기본 기능 테스트 예시
*/
public function test_asserting_a_json_paths_value(): void
{
$response = $this->postJson('/user', ['name' => '홍길동']);
$response
->assertStatus(201)
->assertJsonPath('team.owner.name', '김철수');
}
}assertJsonPath 메서드는 클로저도 받을 수 있습니다. 클로저가 true를 반환하면 assertion이 통과합니다.
$response->assertJsonPath('team.owner.name', fn (string $name) => strlen($name) >= 3);Fluent JSON 테스트
Laravel은 JSON 응답을 보다 유창하게(fluently) 테스트할 수 있는 방법을 제공합니다. assertJson 메서드에 클로저를 전달하면 Illuminate\Testing\Fluent\AssertableJson 인스턴스를 받아 다양한 assertion을 체이닝할 수 있습니다. where 메서드로 특정 속성 값을 검증하고, missing 메서드로 특정 속성이 없음을 검증할 수 있습니다.
Pest
use Illuminate\Testing\Fluent\AssertableJson;
test('fluent JSON 테스트', function () {
$response = $this->getJson('/users/1');
$response
->assertJson(fn (AssertableJson $json) =>
$json->where('id', 1)
->where('name', '홍길동')
->where('email', fn (string $email) => str($email)->is('hong@example.com'))
->whereNot('status', 'pending')
->missing('password')
->etc()
);
});PHPUnit
use Illuminate\Testing\Fluent\AssertableJson;
/**
* 기본 기능 테스트 예시
*/
public function test_fluent_json(): void
{
$response = $this->getJson('/users/1');
$response
->assertJson(fn (AssertableJson $json) =>
$json->where('id', 1)
->where('name', '홍길동')
->where('email', fn (string $email) => str($email)->is('hong@example.com'))
->whereNot('status', 'pending')
->missing('password')
->etc()
);
}etc 메서드 이해하기
위 예시에서 assertion 체인 마지막에 etc 메서드를 호출한 것을 볼 수 있습니다. 이 메서드는 JSON 객체에 assertion하지 않은 다른 속성이 있을 수 있음을 Laravel에 알립니다. etc를 사용하지 않으면, assertion하지 않은 속성이 JSON 객체에 존재할 경우 테스트가 실패합니다.
이 동작의 목적은 JSON 응답에서 민감한 정보가 의도치 않게 노출되는 것을 방지하는 것입니다. 모든 속성에 명시적으로 assertion하거나 etc로 추가 속성을 허용하도록 강제합니다.
단, etc를 사용하지 않더라도 JSON 객체 안에 중첩된 배열에 속성이 추가되는 것까지는 막지 못합니다. etc 메서드는 해당 메서드가 호출된 중첩 수준에서만 추가 속성이 없음을 보장합니다.
속성 존재 여부 검증
has와 missing 메서드로 속성이 존재하는지 또는 없는지 검증할 수 있습니다.
$response->assertJson(fn (AssertableJson $json) =>
$json->has('data')
->missing('message')
);hasAll과 missingAll 메서드를 사용하면 여러 속성의 존재 여부를 한 번에 검증할 수 있습니다.
$response->assertJson(fn (AssertableJson $json) =>
$json->hasAll(['status', 'data'])
->missingAll(['message', 'code'])
);hasAny 메서드는 지정한 속성 중 하나 이상이 존재하는지 확인합니다.
$response->assertJson(fn (AssertableJson $json) =>
$json->has('status')
->hasAny('data', 'message', 'code')
);JSON 컬렉션 검증
라우트가 여러 사용자 등 여러 항목을 포함하는 JSON 응답을 반환하는 경우가 많습니다.
Route::get('/users', function () {
return User::all();
});이런 경우 has 메서드를 사용해 응답에 포함된 사용자 수를 검증하거나, first 메서드로 첫 번째 항목에 대한 assertion을 할 수 있습니다.
$response
->assertJson(fn (AssertableJson $json) =>
$json->has(3)
->first(fn (AssertableJson $json) =>
$json->where('id', 1)
->where('name', '홍길동')
->where('email', fn (string $email) => str($email)->is('hong@example.com'))
->missing('password')
->etc()
)
);컬렉션의 모든 항목에 동일한 assertion을 적용하려면 each 메서드를 사용하세요.
$response
->assertJson(fn (AssertableJson $json) =>
$json->has(3)
->each(fn (AssertableJson $json) =>
$json->whereType('id', 'integer')
->whereType('name', 'string')
->whereType('email', 'string')
->missing('password')
->etc()
)
);이름이 있는 JSON 컬렉션 검증
라우트가 키 이름이 붙은 JSON 컬렉션을 반환하는 경우도 있습니다.
Route::get('/users', function () {
return [
'meta' => [...],
'users' => User::all(),
];
})이런 경우 has 메서드로 컬렉션 항목 수를 검증하거나, assertion 범위를 좁힐 수 있습니다.
$response
->assertJson(fn (AssertableJson $json) =>
$json->has('meta')
->has('users', 3)
->has('users.0', fn (AssertableJson $json) =>
$json->where('id', 1)
->where('name', '홍길동')
->where('email', fn (string $email) => str($email)->is('hong@example.com'))
->missing('password')
->etc()
)
);has를 두 번 호출하는 대신, 세 번째 인수로 클로저를 전달하면 자동으로 컬렉션의 첫 번째 항목에 대해 실행됩니다.
$response
->assertJson(fn (AssertableJson $json) =>
$json->has('meta')
->has('users', 3, fn (AssertableJson $json) =>
$json->where('id', 1)
->where('name', '홍길동')
->where('email', fn (string $email) => str($email)->is('hong@example.com'))
->missing('password')
->etc()
)
);JSON 타입 검증
JSON 응답의 속성이 특정 타입인지만 검증하려면 whereType과 whereAllType 메서드를 사용하세요.
$response->assertJson(fn (AssertableJson $json) =>
$json->whereType('id', 'integer')
->whereAllType([
'users.0.name' => 'string',
'meta' => 'array'
])
);| 문자를 사용하거나 타입 배열을 전달하면 여러 타입 중 하나라도 일치하면 통과합니다.
$response->assertJson(fn (AssertableJson $json) =>
$json->whereType('name', 'string|null')
->whereType('id', ['string', 'integer'])
);whereType과 whereAllType 메서드가 지원하는 타입: string, integer, double, boolean, array, null
파일 업로드 테스트
Illuminate\Http\UploadedFile 클래스의 fake 메서드를 사용하면 테스트용 가짜 파일이나 이미지를 생성할 수 있습니다. 이를 Storage 파사드의 fake 메서드와 함께 사용하면 파일 업로드 테스트를 간단하게 작성할 수 있습니다. 아래는 프로필 이미지 업로드를 테스트하는 예시입니다.
Pest
<?php
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
test('프로필 이미지를 업로드할 수 있다', function () {
Storage::fake('avatars');
$file =