Приложение отправляет уведомления пользователям через SMS.
class SmsService {
sendSms(number: string, message: string): void {
// Логика отправки SMS
}
}
class NotificationManager {
constructor(private smsService: SmsService) {}
notifyUser(user: User, message: string): void {
this.smsService.sendSms(user.phoneNumber, message);
}
}Антипаттерн:
В тестах мокируется конкретный класс
SmsService.describe('NotificationManager', () => {
it('should send SMS notification', () => {
const smsService = new SmsService();
spyOn(smsService, 'sendSms');
const manager = new NotificationManager(smsService);
manager.notifyUser({ phoneNumber: '1234567890' }, 'Test Message');
expect(smsService.sendSms).toHaveBeenCalledWith('1234567890', 'Test Message');
});
});Почему это плохо:
✖Привязывает тест к конкретной реализации.
✖Трудно заменить SmsService на другую реализацию (например, для разных стран).
✅Решение:
Использовать интерфейс для абстракции сервиса отправки сообщений.
interface IMessageService {
sendMessage(recipient: string, message: string): void;
}
class SmsService implements IMessageService {
sendMessage(recipient: string, message: string): void {
// Логика отправки SMS
}
}
class NotificationManager {
constructor(private messageService: IMessageService) {}
notifyUser(user: User, message: string): void {
this.messageService.sendMessage(user.phoneNumber, message);
}
}
🔎Тестирование с мокированием интерфейса:
describe('NotificationManager', () => {
it('should send message notification', () => {
const messageService: IMessageService = {
sendMessage: jasmine.createSpy('sendMessage'),
};
const manager = new NotificationManager(messageService);
manager.notifyUser({ phoneNumber: '1234567890' }, 'Test Message');
expect(messageService.sendMessage).toHaveBeenCalledWith('1234567890', 'Test Message');
});
});😉Что-то вроде выводов:
Стремитесь писать тесты, которые проверяют поведение через публичный интерфейс и фокусируются на результатах, а не на деталях реализации. Это сделает ваш код более надежным, а тесты — более ценными инструментами в процессе разработки.
Теги: #cleanСode #unitTests #TDD #BDD