• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

The Art of Mocking in Backend Tests

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,483
Баллы
155


One thing that hits you fast when you're building anything beyond to-do apps is this: testing matters. That “everything works on my machine” feeling? Doesn’t mean a thing in production.

But here's the thing... testing real dependencies in every test? That’s a pain. Slow tests. External services failing. APIs rate-limiting you. And now your tests are flaky, annoying, and worst of all, unreliable.

That’s where mocks come in like the chill friend that helps you focus on your actual code without worrying about the rest of the world blowing up.

💡 What’s Testing Without Mocks Like?


Let’s paint the scene.

You’ve got a service that pulls data from an external API or database. You write a test, and it:

  • Sends a real HTTP request ☁
  • Connects to a real database 🧱
  • Waits... ⏳
  • Sometimes fails because the API is down 😮💨

Now imagine you’re running this test 50 times across different components. That’s not just fragile; it’s slow, noisy, and way too close to production for comfort.

🤝 Enter Mocks: Your Test Double


Mocks let you fake the parts of your system that don’t need to run for real in a test. Whether it’s an external API, a DB call, or even a complex function you mock it so your test can focus on the logic it’s actually meant to test.

Think of it like this:

You’re not trying to see if your third-party email API sends an actual email.
You’re just checking: did my app call the "SendEmail()" function with the right args?
🔧 So How Do Mocks Actually Work?


Behind the scenes, a mock replaces a real dependency with a controlled fake version that you can:

  • Pre-program to return specific values
  • Track: was it called? how many times?
  • Control: simulate errors, slow responses, etc.

Some mock tools even auto-generate mock code for your interfaces. It's vibes.

🧰 Mock Libraries You Should Know

📦 Node.js (JavaScript/TypeScript)

  1. Jest

const sendEmail = jest.fn();
sendEmail.mockReturnValue('sent');
expect(sendEmail).toHaveBeenCalled();



  1. Sinon

const mock = sinon.mock(myService);
mock.expects("getUser").once().returns({ name: "Mike" });



🐹 GoLang

  1. Testify (Mock Package)

type MockEmailService struct {
mock.Mock
}

func (m *MockEmailService) Send(to string, body string) error {
args := m.Called(to, body)
return args.Error(0)
}

emailMock := new(MockEmailService)
emailMock.On("Send", "user@example.com", "Hi").Return(nil)



  1. GoMock (Google’s Official Mocking Framework)
🧪 Real World Example: Testing a Signup Flow


Let’s say you’ve got a signupUser function that does the following:

  • Saves the user to DB
  • Sends a welcome email
  • Logs a signup event

You don’t want your test to:

  • Actually save to the DB
  • Actually send an email
  • Actually log events to a service

You want to mock those services and just check:

“Hey, did they get called when I expected them to?”
🚀 Benefits of Using Mocks

  • ✅ Faster tests (no real network calls)
  • ✅ More reliable (no flaky external failures)
  • ✅ Easier to isolate logic
  • ✅ Lets you simulate edge cases & errors easily
  • ✅ Clean architecture (forces you to use interfaces 👀)
💭 Final Thoughts


Mocking is one of those testing tools that once you get it, you never stop using it. It's not about skipping real tests—those still matter. It’s about giving your core logic a safe, fast sandbox to play in.

If you're serious about backend dev, mocking should absolutely be in your toolbox.

🧵 TL;DR:

  • Don’t test real dependencies every time.
  • Mock services you don’t control or don’t need to verify deeply.
  • Use jest, sinon, testify/mock, or gomock depending on your stack.
  • Write tests that are focused, fast, and less flaky.



Источник:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу