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