Here are my Top 5 Naming Patterns for Unit Tests in C#

NET category image

Naming tests is an underrated part of the testing process. Here are 5 patterns that you can use to keep your test names consistent.

Why is naming important?

Naming tests is an important task to write maintainable code. A good naming convention allows other developers to quickly recognize the purpose of a test. Therefore, a lot of patterns have been created over the years. I’ll introduce the most common ones. You can use them or come up with your own variant. Being consistent and understandable is the key.

Given When Then

The Given When Then pattern is used a lot in Behavior-Driven Development. It defines preconditions (Given), an action (When), and a result (Then). This leads to very long, but easily understandable test names.

▶ GivenDatabaseIsUp_WhenUserInputIsValid_ThenUserIsCreated

Here is an article that describes how to use BDD with C#

When Then

The When Then pattern is similar to the Given When Then pattern but omits any preconditions. Names will be shorter, but most likely not as understandable. This is similar to the Should When approach.

▶ WhenUserInputIsValid_ThenUserIsCreated

Should

The Should pattern gives a hint of what a test should check for. This is similar to the Verify approach.

▶ ShouldCreateUserInDatabase

Want More Flutter Content?

Join my bi-weekly newsletter that delivers small Flutter portions right in your inbox. A title, an abstract, a link, and you decide if you want to dive in!

Should When

The Should When pattern indicates the outcome of a test by including a condition. It’s more verbose than the Should approach and tends to be more understandable. This is similar to the When Then approach.

▶ ShouldCreateUserInDatabaseWhenInputIsValid

Verify

The Verify approach tells a user what the outcome of a test should be. This is similar to the Should approach.

▶ VerifyCreateUserInDatabase

Conclusion

From my experiences, these patterns cover the majority of unit tests that I have seen so far. No matter what you choose, just be consistent. It’s confusing to find multiple naming patterns in a code base.


Want More Flutter Content?

Join my bi-weekly newsletter that delivers small Flutter portions right in your inbox. A title, an abstract, a link, and you decide if you want to dive in!