Writing unit tests might sound like a boring task, but it’s what separates a professional developer from someone who’s just playing with code.
Unit tests are small, automated tests that check if a specific part of your program (called a "unit") works as expected.
The faster and more reliable your unit tests are, the easier your life becomes as a developer. That’s where the FIRST principles come in.
Let me walk you through this step by step:
⚡ F - Fast
Fast tests are a must. If your tests take minutes to run, you’ll avoid running them—and that’s where the trouble begins.
Picture this:
- 🦸♂️ Tests that run in seconds? You’ll run them constantly.
- 😕 Tests that take minutes? Maybe once or twice a day.
- 🪦 Tests that take hours? Forget it—you’ll stop running them altogether.
The solution? Write simple, focused tests that don’t rely on the internet, databases, or large file systems.
A clean unit test should run so fast that you barely notice it happening.
🫙 I - Isolated
Each test should focus on one specific thing.
A test that relies on external factors like a slow network or shared data is asking for trouble. Why? Because it can fail for reasons unrelated to the code you’re testing.
Make sure each test:
- 🔭 Stands on its own.
- 🌖 Has one clear purpose.
- ⛓️💥 Fails for a single reason, making debugging easy.
Isolation keeps your tests clean, predictable, and manageable.
🔁 R - Repeatable
A good unit test always gives the same result, no matter how many times you run it.
If a test works sometimes but fails other times, it’s unreliable. This can happen because of:
- 🚚 Static data not being reset.
- 🌦️ Dependence on external systems like APIs.
- ❌ Incorrect use of threads or processes.
To fix this, write tests that are fully controlled by your code—nothing external. This makes your tests repeatable and trustworthy.
✅ S - Self-Verifying
A unit test should clearly pass or fail. No guessing.
If you have to manually check logs or interpret the results, your test isn’t self-verifying. A good test is like a green light or a red light—no gray areas.
When your tests are self-verifying, you can trust the results and move forward confidently.
⏳ T - Timely
Write your tests before you write your code.
This is known as Test-Driven Development (TDD) and it forces you to think about what your code should do before you build it.
Tests written later (Test-After Development, or TAD) are often incomplete, hard to write, and less useful.
Writing tests first makes your code:
- 🧠 Easier to understand.
- 🎭 Designed with clarity in mind.
- 🪁 Free from unnecessary complexity.
Thank you for your time. Make sure to leave a comment if you have any questions.
Top comments (0)