왜 모킹을 사용하는가
테스트를 작성할 때 메일 발송·캐시 읽기/쓰기·외부 API 호출 등 실제로는 실행하고 싶지 않은 처리가 있습니다.
이러한 처리를 “진짜인 척하는 가짜”로 대체하는 것을 모킹이라고 합니다.
모킹을 사용하면 다음과 같은 이점이 있습니다.
- 테스트가 빠릅니다 — 외부 서비스나 무거운 처리를 실행하지 않으므로 테스트가 곧바로 끝납니다
- 테스트가 안정적입니다 — 외부 서비스의 상태에 좌우되지 않고 항상 동일한 결과가 나옵니다
- 테스트의 범위가 명확해집니다 — 하나의 클래스나 메서드만 검증할 수 있습니다
Laravel은 이벤트·잡·파사드 등의 모킹을 곧바로 사용할 수 있는 헬퍼를 제공합니다.
내부적으로는 Mockery를 사용하고 있으며, 복잡한 설정 없이 이용할 수 있습니다.
모의 객체
서비스 컨테이너를 통해 주입되는 객체를 모킹하려면 모의 인스턴스를 컨테이너에 바인딩합니다.
이렇게 하면 컨테이너는 객체를 생성하는 대신 모의 인스턴스를 사용합니다.
use App\Service;
use Mockery;
use Mockery\MockInterface;
test('something can be mocked', function () {
$this->instance(
Service::class,
Mockery::mock(Service::class, function (MockInterface $mock) {
$mock->expects('process');
})
);
});
use App\Service;
use Mockery;
use Mockery\MockInterface;
public function test_something_can_be_mocked(): void
{
$this->instance(
Service::class,
Mockery::mock(Service::class, function (MockInterface $mock) {
$mock->expects('process');
})
);
}
mock() 메서드
Laravel의 테스트 케이스 베이스 클래스가 제공하는 mock() 메서드를 사용하면 위와 동일한 처리를 더 간결하게 작성할 수 있습니다.
use App\Service;
use Mockery\MockInterface;
$mock = $this->mock(Service::class, function (MockInterface $mock) {
$mock->expects('process');
});
partialMock() 메서드
객체의 일부 메서드만 모킹하고 싶다면 partialMock()을 사용합니다.
모킹하지 않은 메서드는 평소대로 실행됩니다.
use App\Service;
use Mockery\MockInterface;
$mock = $this->partialMock(Service::class, function (MockInterface $mock) {
$mock->expects('process');
});
spy() 메서드
스파이는 모의와 비슷하지만 코드 실행 후에 상호 작용을 검증한다는 점이 다릅니다.
모의가 “이 메서드가 호출될 것이다”라고 사전에 설정하는 반면, 스파이는 “이 메서드가 호출되었는지”를 사후에 확인합니다.
use App\Service;
$spy = $this->spy(Service::class);
// ...테스트 대상 코드를 실행...
$spy->shouldHaveReceived('process');
파사드 모킹
파사드는 일반적인 정적 메서드 호출과 달리 모킹이 가능합니다.
의존성 주입과 동등한 테스트 용이성을 유지하면서도 간결한 문법으로 작성할 수 있습니다.
예를 들어 캐시를 사용하는 컨트롤러를 살펴봅시다.
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Cache;
class UserController extends Controller
{
/**
* 애플리케이션의 전체 사용자 목록을 반환
*/
public function index(): array
{
$value = Cache::get('key');
return [
// ...
];
}
}
Cache 파사드의 get 메서드를 모킹하려면 expects()를 사용합니다.
<?php
use Illuminate\Support\Facades\Cache;
test('get index', function () {
Cache::expects('get')
->with('key')
->andReturn('value');
$response = $this->get('/users');
// ...
});
<?php
namespace Tests\Feature;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
class UserControllerTest extends TestCase
{
public function test_get_index(): void
{
Cache::expects('get')
->with('key')
->andReturn('value');
$response = $this->get('/users');
// ...
}
}
Request 파사드는 모킹하지 마세요. 대신 get이나 post 등의 HTTP 테스트 메서드에 입력 값을 전달하세요. 마찬가지로 Config 파사드를 모킹하는 대신 테스트 내에서 Config::set()을 호출하세요.
파사드 스파이
파사드를 스파이로 감시하려면 해당 파사드의 spy() 메서드를 호출합니다.
스파이는 코드가 실행된 후에 상호 작용을 검증하고 싶을 때 편리합니다.
<?php
use Illuminate\Support\Facades\Cache;
test('values are stored in cache', function () {
Cache::spy();
$response = $this->get('/');
$response->assertStatus(200);
Cache::shouldHaveReceived('put')->with('name', 'Taylor', 10);
});
use Illuminate\Support\Facades\Cache;
public function test_values_are_stored_in_cache(): void
{
Cache::spy();
$response = $this->get('/');
$response->assertStatus(200);
Cache::shouldHaveReceived('put')->with('name', 'Taylor', 10);
}
시간 조작
시간에 의존하는 로직을 테스트에서 검증할 때, now()나 Carbon::now()가 반환하는 시각을 변경할 수 있으면 편리합니다.
Laravel의 기능 테스트 베이스 클래스에는 시간을 조작하기 위한 헬퍼가 준비되어 있습니다.
travel() — 시간을 이동시키기
test('time can be manipulated', function () {
// 미래로 이동
$this->travel(5)->milliseconds();
$this->travel(5)->seconds();
$this->travel(5)->minutes();
$this->travel(5)->hours();
$this->travel(5)->days();
$this->travel(5)->weeks();
$this->travel(5)->years();
// 과거로 이동
$this->travel(-5)->hours();
// 특정 시각으로 이동
$this->travelTo(now()->subHours(6));
// 현재 시각으로 복귀
$this->travelBack();
});
public function test_time_can_be_manipulated(): void
{
// 미래로 이동
$this->travel(5)->milliseconds();
$this->travel(5)->seconds();
$this->travel(5)->minutes();
$this->travel(5)->hours();
$this->travel(5)->days();
$this->travel(5)->weeks();
$this->travel(5)->years();
// 과거로 이동
$this->travel(-5)->hours();
// 특정 시각으로 이동
$this->travelTo(now()->subHours(6));
// 현재 시각으로 복귀
$this->travelBack();
}
클로저를 사용한 시간 이동
시간 이동 메서드에 클로저를 전달하면 지정한 시각에서 시간을 멈추고 클로저를 실행한 뒤, 완료 후 원래 시각으로 되돌아갑니다.
$this->travel(5)->days(function () {
// 5일 후 상태에서 테스트
});
$this->travelTo(now()->subDays(10), function () {
// 특정 순간에서 테스트
});
freezeTime() — 시간을 멈추기
freezeTime()은 현재 시각을 고정합니다. freezeSecond()는 현재 시각을 초 단위 시작점에서 고정합니다.
use Illuminate\Support\Carbon;
// 시간을 고정하고 클로저를 실행하며, 종료 후 재개
$this->freezeTime(function (Carbon $time) {
// ...
});
// 현재 초의 시작 시점에 고정하고 클로저 실행
$this->freezeSecond(function (Carbon $time) {
// ...
});
실용 예시: 비활성 스레드의 잠금
시간 조작은 일정 기간 동안 조작이 없으면 게시글이 잠기는 포럼과 같은 기능을 테스트할 때 유용합니다.
use App\Models\Thread;
test('forum threads lock after one week of inactivity', function () {
$thread = Thread::factory()->create();
$this->travel(1)->week();
expect($thread->isLockedByInactivity())->toBeTrue();
});
use App\Models\Thread;
public function test_forum_threads_lock_after_one_week_of_inactivity(): void
{
$thread = Thread::factory()->create();
$this->travel(1)->week();
$this->assertTrue($thread->isLockedByInactivity());
}
travel() 등의 시간 조작 메서드는 기능 테스트(Tests\TestCase를 상속받은 클래스)에서만 사용할 수 있습니다. PHPUnit의 기본 TestCase에서는 사용할 수 없습니다.
메서드 목록
모킹 관련
| 메서드 | 설명 |
|---|
$this->mock(Class::class, fn) | 클래스의 완전한 모의를 생성하고 컨테이너에 등록 |
$this->partialMock(Class::class, fn) | 일부 메서드만 모킹 |
$this->spy(Class::class) | 스파이를 생성하고 컨테이너에 등록 |
$this->instance(Class::class, $mock) | 임의의 모의 인스턴스를 컨테이너에 등록 |
Facade::expects('method') | 파사드의 메서드를 모킹 |
Facade::spy() | 파사드를 스파이로 감시 |
$spy->shouldHaveReceived('method') | 스파이에 대해 메서드가 호출되었는지 검증 |
시간 조작 관련
| 메서드 | 설명 |
|---|
$this->travel(n)->unit() | 지정한 단위만큼 시간 이동 |
$this->travelTo(Carbon) | 특정 시각으로 이동 |
$this->travelBack() | 현재 시각으로 복귀 |
$this->freezeTime(fn) | 시간을 고정하고 클로저 실행 |
$this->freezeSecond(fn) | 초 단위 시작점에서 시간 고정하고 클로저 실행 |