DEV Community

Cover image for Unit Testing Best Practices: Organization & Test Data
Cesar Aguirre
Cesar Aguirre

Posted on • Updated on • Originally published at canro91.github.io

Unit Testing Best Practices: Organization & Test Data

I originally posted an extended version of this post on my blog a couple of weeks ago. It's part of a series I've been publishing, called Unit Testing 101


Do you want to write better unit tests? Do you keep your unit tests organized? And, do you write your tests at the right level of abstraction? These are some best practices on Test Organization and Test Data.

On Organization

Make your tests easy to find.

1. Put your unit tests in a test project named after the project they test. Use the suffix "Tests" or "UnitTests". For example, if you have a library called MyLibrary, name your test project: MyLibrary.UnitTests.

2. Put your unit tests separated in files named after the unit of work or entry point of the code you're testing. Use the suffix "Tests". For a class MyClass, name your test file: MyClassTests.

On Test Data

Keep the amount of details at the right level

3. Give enough details to your readers, but not too many to make your tests noisy.

4. Use factory methods to reduce complex Arrange scenarios.

5. Make your scenario under test and test values extremely obvious. Don't make developers to decode your tests. Create constants for common test data and expected values.

6. Use object mothers to create input test values. Have a factory method or property holding a ready-to-use input object. Then, change what you need to match the scenario under test.

7. Prefer Builders to create complex object graphs. Object mothers are fine if you don't have lots of variations of the object being constructed. If that's the case, use the Builder pattern. Compose builders to create complex objects in your tests.

Voilà! Those are some tips to get our tests organized and without clutter.

Remember, keep your unit tests separated into projects and classes and write your tests at the right level of abstraction using builders and factory methods.


Upgrade your unit testing skills with my course: Mastering C# Unit Testing with Real-world Examples on Udemy. Practice with hands-on exercises and learn best practices by refactoring real-world unit tests.

Happy testing!

Top comments (0)