TGViewer
QA Family by Alexey QA Family by Alexey @dev_qa · 1.63K subscribers
Post #226 1.25K
🔎Мокирование конкретных классов вместо интерфейсов
Приложение отправляет уведомления пользователям через 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
  • 👎 63
  • 👍 12
  • ❤ 3
More from @dev_qa
  1. Sep 23, 2026Следующий спикер митапа Moscow QA #28 x Черный митап +18 Даниил Ахетов с докладом Как я де…
  2. Sep 23, 2026Приходите будет еще Боря, Костя и Саша из PiterQA Все топовые спикеры которые расскажут ве…
  3. Sep 5, 2026Ссылка на трансляцию митапа Moscow QA#27 x Мир Plat.Form: https://vkvideo.ru/video-2052808…
  4. Sep 5, 2026Vitest 5.0 вышел ➖ trace view в Browser Mode: упавший браузерный тест проигрывается по шаг…
  5. Sep 1, 2026Playwright MCP 0.0.80 добавлены инструменты browser_start_recording / browser_stop_recordi…
  6. Aug 26, 2026Post #339
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →