Fakes

Fakes Fakes는 Test Double 기법 중 하나로, 실제 객체의 간단한 구현을 제공하는 테스트용 객체. 목적 실제 구현체를 단순화하여 테스트 환경에서 사용한다. 외부 의존성을 제거하고 테스트 속도를 향상시킨다. 실제 객체와 유사한 동작을 제공하여 현실적인 테스트 환경을 구성한다. 장점 테스트 실행 속도가 빠르다. 실제 구현체보다 구성이 간단하다. 테스트 간 재사용이 용이하다. 실제 객체와 유사한 동작으로 신뢰성 있는 테스트가 가능하다. 단점 실제 구현체와 동작이 완전히 일치하지 않을 수 있다. Fake 객체 구현에 추가적인 시간과 노력이 필요하다. Fake 객체 자체의 유지보수가 필요할 수 있다. 예시 Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class RealDatabase: def connect(self): # 실제 데이터베이스 연결 로직 pass def fetch_data(self): # 실제 데이터 조회 로직 return "Real data" class FakeDatabase: def connect(self): # 연결 시뮬레이션 pass def fetch_data(self): # 가짜 데이터 반환 return "Fake data" class DataService: def __init__(self, database): self.database = database def get_data(self): self.database.connect() return self.database.fetch_data() # 테스트 fake_db = FakeDatabase() data_service = DataService(fake_db) result = data_service.get_data() assert result == "Fake data" JavaScript 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 class RealDatabase { connect() { // 실제 데이터베이스 연결 로직 } fetchData() { // 실제 데이터 조회 로직 return "Real data"; } } class FakeDatabase { connect() { // 연결 시뮬레이션 } fetchData() { // 가짜 데이터 반환 return "Fake data"; } } class DataService { constructor(database) { this.database = database; } getData() { this.database.connect(); return this.database.fetchData(); } } // 테스트 const fakeDb = new FakeDatabase(); const dataService = new DataService(fakeDb); const result = dataService.getData(); console.assert(result === "Fake data"); 참고 및 출처

November 1, 2024 · 2 min · Me

Dummy Objects

Dummy Objects 테스트 과정에서 실제로는 사용되지 않지만 메서드의 파라미터를 채우기 위해 전달되는 객체 Dummy Objects는 Test Double 기법 중 하나로, 테스트에 필요하지만 실제로 사용되지 않는 객체를 의미합니다. 목적 테스트 대상 코드의 인터페이스 요구사항을 충족시키기 위해 사용된다. 테스트 실행을 위해 필요하지만 테스트 자체와는 관련이 없는 객체를 대체한다. 장점 테스트 코드를 단순화하고 가독성을 높인다. 불필요한 객체 생성을 피해 테스트 성능을 향상시킨다. 테스트 대상 코드를 외부 의존성으로부터 격리시킨다. 단점 실제 객체의 동작을 정확히 반영하지 않을 수 있다. 과도한 사용 시 테스트의 현실성이 떨어질 수 있다. 예시 Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 # 실제 이메일 서비스 클래스 class EmailService: def __init__(self, smtp_server, port): self.smtp_server = smtp_server self.port = port def send_notification(self, user, message): # 실제로는 이메일을 보내는 복잡한 로직이 있을 것입니다 print(f"Sending email to {user.email}: {message}") # 사용자 클래스 class User: def __init__(self, name, email, notification_service): self.name = name self.email = email self.notification_service = notification_service def notify_login(self): self.notification_service.send_notification( self, f"New login detected for {self.name}" ) # Dummy 객체 class DummyEmailService: def __init__(self, smtp_server=None, port=None): pass # 아무것도 하지 않음 def send_notification(self, user, message): pass # 아무것도 하지 않음 # 테스트 코드 def test_user_creation(): # Dummy 이메일 서비스 사용 dummy_email_service = DummyEmailService() # 실제로 테스트하고 싶은 것은 사용자 생성 로직입니다 user = User("John Doe", "john@example.com", dummy_email_service) assert user.name == "John Doe" assert user.email == "john@example.com" JavaScript 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 // 실제 로깅 서비스 클래스 class LoggerService { constructor(logLevel) { this.logLevel = logLevel; } log(message) { // 실제로는 로그를 저장하는 복잡한 로직이 있을 것입니다 console.log(`[${this.logLevel}] ${message}`); } } // 사용자 관리 클래스 class UserManager { constructor(logger) { this.logger = logger; this.users = []; } addUser(user) { this.users.push(user); this.logger.log(`User ${user.name} added`); return this.users.length; } } // Dummy 로거 class DummyLogger { constructor(logLevel) { // 아무것도 저장하지 않음 } log(message) { // 아무것도 하지 않음 } } // 테스트 코드 describe('UserManager', () => { it('should add a new user correctly', () => { // Dummy 로거 사용 const dummyLogger = new DummyLogger(); const userManager = new UserManager(dummyLogger); // 실제로 테스트하고 싶은 것은 사용자 추가 로직입니다 const userCount = userManager.addUser({ name: 'John' }); expect(userCount).toBe(1); expect(userManager.users.length).toBe(1); }); }); 참고 및 출처

November 1, 2024 · 2 min · Me

Spies

Spies Spies는 Test Double 기법 중 하나로, 실제 객체의 메서드 호출을 추적하고 기록하는 데 사용된다. 목적 메서드 호출 여부, 횟수, 전달된 인자 등을 검증한다. 실제 구현을 변경하지 않고 메서드의 동작을 관찰한다. 코드의 상호작용을 분석하고 테스트한다. 장점 비침투적: 실제 객체의 동작을 변경하지 않고 관찰할 수 있다. 유연성: 다양한 정보를 수집하고 검증할 수 있다. 상세한 검증: 메서드 호출의 세부 사항을 정확히 확인할 수 있다. 단점 복잡성: 과도한 사용 시 테스트 코드가 복잡해질 수 있다. 오버스펙: 구현 세부사항에 너무 의존적인 테스트를 작성할 위험이 있다. 성능: 많은 spy를 사용할 경우 테스트 실행 속도가 느려질 수 있다. 예시 예시 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 from typing import Dict, Optional from datetime import datetime # 실제 데이터베이스 리포지토리 class UserRepository: def __init__(self, database_connection): self.db = database_connection def save(self, user_id: str, user_data: Dict): # 실제로는 데이터베이스에 SQL 쿼리를 실행할 것입니다 self.db.execute( "INSERT INTO users (id, data, created_at) VALUES (?, ?, ?)", [user_id, user_data, datetime.now()] ) def find_by_id(self, user_id: str) -> Optional[Dict]: # 실제로는 데이터베이스에서 조회할 것입니다 result = self.db.execute( "SELECT * FROM users WHERE id = ?", [user_id] ) return result.fetchone() # Fake 리포지토리 class FakeUserRepository: def __init__(self): # 데이터베이스 대신 딕셔너리를 사용 self.users: Dict[str, Dict] = {} def save(self, user_id: str, user_data: Dict): # 메모리에 직접 저장 self.users[user_id] = { 'data': user_data, 'created_at': datetime.now() } def find_by_id(self, user_id: str) -> Optional[Dict]: # 메모리에서 직접 조회 return self.users.get(user_id) # 사용자 서비스 class UserService: def __init__(self, user_repository): self.repository = user_repository def create_user(self, user_id: str, name: str, email: str): user_data = {'name': name, 'email': email} self.repository.save(user_id, user_data) def get_user(self, user_id: str): return self.repository.find_by_id(user_id) # 테스트 코드 def test_user_service(): # Fake 리포지토리 사용 fake_repository = FakeUserRepository() user_service = UserService(fake_repository) # 사용자 생성 테스트 user_service.create_user('user1', 'John Doe', 'john@example.com') # 사용자 조회 테스트 user = user_service.get_user('user1') assert user['data']['name'] == 'John Doe' assert user['data']['email'] == 'john@example.com' JavaScript 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 // 실제 외부 API 서비스 class WeatherService { async getTemperature(city) { // 실제로는 외부 API를 호출할 것입니다 const response = await fetch( `https://api.weather.com/${city}/temperature` ); return response.json(); } } // Fake 날씨 서비스 class FakeWeatherService { constructor() { // 미리 정의된 도시별 온도 데이터 this.temperatureData = { 'Seoul': { temperature: 25 }, 'New York': { temperature: 20 }, 'London': { temperature: 15 } }; } async getTemperature(city) { // 실제 API 호출 대신 저장된 데이터 반환 return Promise.resolve(this.temperatureData[city] || { temperature: 0 }); } } // 날씨 알림 서비스 class WeatherAlertService { constructor(weatherService) { this.weatherService = weatherService; } async shouldSendAlert(city) { const data = await this.weatherService.getTemperature(city); return data.temperature > 30; } } // 테스트 코드 describe('WeatherAlertService', () => { it('should not send alert for normal temperature', async () => { // Fake 날씨 서비스 사용 const fakeWeatherService = new FakeWeatherService(); const alertService = new WeatherAlertService(fakeWeatherService); const shouldAlert = await alertService.shouldSendAlert('Seoul'); expect(shouldAlert).toBe(false); }); }); 참고 및 출처

November 1, 2024 · 3 min · Me

Stubs

Stubs Stubbing은 테스트에서 사용되는 기법으로, 실제 객체나 아직 구현되지 않은 코드를 대신하여 미리 정의된 응답을 제공하는 메커니즘 목적 의존성 격리: 실제 구현체로부터 테스트 대상을 분리하여 독립적인 테스트를 가능하게 합니다. 특정 시나리오 테스트: 다양한 상황에 대한 테스트를 용이하게 합니다. 미구현 코드 대체: 아직 개발되지 않은 부분을 임시로 대체할 수 있습니다. 테스트 속도 향상: 실제 리소스 접근 없이 빠른 테스트가 가능합니다. 특징 미리 정의된 응답(canned answer)을 제공합니다. 실제 코드의 동작을 단순화하여 모사합니다. 주로 상태 테스팅에 중점을 둡니다. 메서드 호출의 결과만 정의하며, 호출 여부는 검증하지 않습니다. 사용 사례 구현되지 않은 함수나 외부 라이브러리 함수를 사용할 때 복잡한 로직을 단순화하여 테스트하고자 할 때 특정 조건에서의 예외 상황을 테스트할 때 외부 의존성(예: 데이터베이스, 네트워크 요청)을 가진 코드를 테스트할 때 예시 Python 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 from unittest.mock import Mock, patch import pytest from datetime import datetime # 테스트할 실제 클래스 class PaymentService: def __init__(self, payment_gateway): self.payment_gateway = payment_gateway def process_payment(self, amount): if amount <= 0: raise ValueError("Amount must be positive") response = self.payment_gateway.charge(amount) if response['status'] == 'success': return True return False # 외부 결제 게이트웨이 클래스 (실제로는 외부 서비스) class PaymentGateway: def charge(self, amount): # 실제로는 외부 API를 호출하는 복잡한 로직 pass # Stub 예시 class PaymentGatewayStub: def charge(self, amount): # 항상 성공 응답을 반환하는 단순한 구현 return {'status': 'success', 'timestamp': datetime.now()} # 테스트 코드 def test_payment_service_with_stub(): # Stub 사용 gateway_stub = PaymentGatewayStub() payment_service = PaymentService(gateway_stub) assert payment_service.process_payment(100) == True Javascript 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 // Jest를 사용한 테스트 예시 const { jest } = require('@jest/globals'); // 테스트할 실제 클래스 class UserService { constructor(database) { this.database = database; } async getUserById(id) { const user = await this.database.findUser(id); if (!user) { throw new Error('User not found'); } return user; } async updateUserEmail(id, newEmail) { const user = await this.database.findUser(id); if (!user) { throw new Error('User not found'); } user.email = newEmail; await this.database.updateUser(id, user); return user; } } // Stub 예시 class DatabaseStub { constructor() { this.users = new Map([ [1, { id: 1, name: 'John Doe', email: 'john@example.com' }], [2, { id: 2, name: 'Jane Doe', email: 'jane@example.com' }] ]); } async findUser(id) { return this.users.get(id); } async updateUser(id, userData) { this.users.set(id, userData); return userData; } } // 테스트 코드 describe('UserService', () => { // Stub을 사용한 테스트 describe('with stub', () => { const dbStub = new DatabaseStub(); const userService = new UserService(dbStub); test('should return user when exists', async () => { const user = await userService.getUserById(1); expect(user.name).toBe('John Doe'); }); test('should throw error when user not found', async () => { await expect(userService.getUserById(999)) .rejects .toThrow('User not found'); }); }); }); 참고 및 출처

November 1, 2024 · 3 min · Me