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

Get Free Daily Flutter Content!

Small daily Flutter portions delivered 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.

Related articles