DEV Community 👩‍💻👨‍💻

Cover image for Unit Testing Best Practices: 6 tips for better names
Cesar Aguirre
Cesar Aguirre

Posted on

Unit Testing Best Practices: 6 tips for better names

Today I'm not posting a 1000-word, SEO-rich article. I'm reposting a LinkedIn post with 6 quick tips to write better test names.

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 you have 6 quick tips/ideas to write better names for your unit tests.

✔️ Choose a naming convention for your test names and stick to it.

✔️ 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.

✔️ Describe in your test names what your testing in a language easy to understand even for non-programmers.

❌ 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.

❌ 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.

❌ Don't use assertion messages. Write better test names.

Voilà! Six tips as promised. If you want to dig deeper into unit testing, I wrote a post on naming conventions for our unit tests and other unit testing best practices. You will find more tips on names, organization and mocks.

Happy testing!

Top comments (0)

Timeless DEV post...

How to write a kickass README

Arguably the single most important piece of documentation for any open source project is the README. A good README not only informs people what the project does and who it is for but also how they use and contribute to it.

If you write a README without sufficient explanation of what your project does or how people can use it then it pretty much defeats the purpose of being open source as other developers are less likely to engage with or contribute towards it.