Some time ago, I wrote an article about naming unit tests. The main takeaways from that article are:
-
Don’t use a rigid test naming policy.
-
Name the tests as if you were describing the scenario in it to a non-programmer who is familiar with the problem domain.
To illustrate these points, I used an example of transforming a test name from this:
public void IsDeliveryValid_InvalidDate_ReturnsFalse()
to this:
public void Delivery_with_a_past_date_is_invalid()
A fellow reader asked an interesting question, which I thought I’d share with you (edited lightly for clarity):
How should I name a test that checks for an ArgumentNullException?
This is something that comes up quite often: how to represent a technical information in a way that is meaningful to a non-programmer?
You need to find business meaning behind these technicalities and put that meaning explicitly into the test name.
For example, if you have a Customer
entity that accepts an email in the constructor and you want to test that no customers can be created without an email, name that test Customer_email_is_required
.
Here’s another example I had recently in the project I’m working on:
[Test] public void Create_returns_ok_when_NameSuffixId_is_null() { Result<CustomerName> validationResult = CustomerName.Create ("first", "last", nameSuffixId: null); validationResult.ShouldBeOk(); }
The test itself is simple but its name lacks clarity.
What does it mean for the Create
method to return OK
when passing null
as the name suffix?
It means that that suffix is not required. Which is a fact that’s best stated explicitly in the name of the test:
public void NameSuffix_is_optional()
This version is much better.
Not only does this name convey the business meaning behind the test, it’s also much shorter.
--Vlad
https://enterprisecraftsmanship.com
Enjoy this message? Here are more things you might like:
Workshops — I offer a 2-day workshop for organizations on Domain-Driven Design and Unit Testing. Reply to this email to discuss.
Unit Testing Principles, Patterns and Practices — A book for people who already have some experience with unit testing and want to bring their skills to the next level.
Learn more »
My Pluralsight courses — The topics include Unit Testing, Domain-Driven Design, and more.
Learn more »