DEV Community

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

Posted on • Originally published at


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.

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.

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

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

Use factory methods to reduce complex Arrange scenarios.

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.

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.

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.

Do you want to see examples of Object Mothers and Builders? Check How to create test data with the Builder pattern where we test a credit card validator.

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.

For more best practices on unit testing, check my posts Unit Testing Best Practices and Let's refactor a unit test.

If you're new to unit testing or want to learn more, stay tune to my "Unit Testing 101" series on my blog Just Some Code.

Happy testing!

Top comments (0)

Advice For Junior Developers

Advice from a career of 15+ years for new and beginner developers just getting started on their journey.