Unit Testing Best Practices: 6 tips for better names
Cesar Aguirre
Posted on October 4, 2021
Often, we don't put too much care into our unit tests, maybe with the excuse that "we don't ship tests to our customers" or "writing tests will take more time, and we don't have time".
But, unit tests are our safety-net, our seat belt. They're there to give us confidence to change things.
Here are 6 quick tips to write better names for your unit tests
✔️ 1. Choose a naming convention for your test and stick to it.
✔️ 2. Every test name should tell the scenario under test and the expected result. Don't worry about long test names. But, don't name your tests: Test1
, Test2
and so on.
✔️ 3. Describe in your test names what your testing in a language easy to understand even for non-programmers.
❌ 4. Don't prefix your test names with "Test". If you're using a testing framework that doesn't need keywords in your test names, don't do that. In C# with MSTest, we have attributes like [TestClass]
and [TestMethod]
to mark classes and methods as tests. Other testing frameworks have similar attributes.
❌ 5. Don't use filler words like "Success" or "IsCorrect" in test names. Instead, tell what "success" and "correct" means for that test. Is it a successful test because it doesn't throw exceptions? because it returns a value? Make your test names easy to understand.
❌ 6. Don't use assertion messages. Write better test names.
Voilà! Six tips as promised. Naming is hard, I know!
If you want to upgrade your unit testing skills, check my course: Mastering C# Unit Testing with Real-world Examples on Udemy. Write readable and maintainable unit tests in 1 hour by refactoring real-world tests — Yes, real tests. No boring tests for a Calculator class.
Happy testing!
Posted on October 4, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.