The Art of Mocking in Backend Tests


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)
- Jest
Built-in mocking support:
jest.fn()
,jest.mock()
Track function calls, set return values, and simulate errors.
const sendEmail = jest.fn();
sendEmail.mockReturnValue('sent');
expect(sendEmail).toHaveBeenCalled();
- Sinon
Great for stubbing, spying, and mocking external dependencies.
const mock = sinon.mock(myService);
mock.expects("getUser").once().returns({ name: "Mike" });
🐹 GoLang
- Testify (Mock Package)
Lets you generate mocks for interfaces
Powerful assertions and control over mock behavior
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)
- GoMock (Google’s Official Mocking Framework)
Slightly more setup-heavy but works beautifully with interfaces
Generates mocks via
mockgen
🧪 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
, orgomock
depending on your stack.Write tests that are focused, fast, and less flaky.
Subscribe to my newsletter
Read articles from m13ha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

m13ha
m13ha
Welcome to my little corner of the internet where business savvy meets coding prowess, all wrapped up in the day-to-day adventures of yours truly. Whether you're here to level up your programming skills, gain some business insights, or just enjoy a slice of life through my eyes, you're in the right place! #CodeLife #BusinessMinded #TechEntrepreneur #ProgrammingAdventures #StartupJourney #DeveloperDiaries #LifeInCode #BusinessAndBytes #TechLifeBalance #CodeEntrepreneur