A unit test should be descriptive. If your colleague is reading your test case then he/she should understand – without spending much effort – what does the test do, what is the expected result and under what conditions.
Naming unit tests has also an impact on the descriptiveness. In general, you should define or pick an existing naming convention and stick to it.
A few unit tests naming conventions do exist. Following are some examples :
- UnitUnderTest_StateUnderTest_ExpectedBehavior
- This is a clean way to name your tests and make them human readable. However you should consider renaming your unit tests if the name of the component under test changes.
- You can also switch the order of StateUnderTest and the ExpectedBehavior.
- Should_ExpectedBehavior_When_StateUnderTest
- This standard is nice but comes with some redundancy by having the term “Should” everywhere in your unit tests.
- When_StateUnderTest_Expect_ExpectedBehavior
- You may notice here that this naming standard does not contain the UnitUnderTest name (method, class, etc). This is OK since we are testing a behavior.
In addition to the above, coding conventions and programming best practices that you follow e when developing production code still apply when you write unit tests. This will make your unit tests more readable and clean.
Example
Consider the calculateTotal() method that calculates the total price of a list of products.
@Test
void test1(){
// as you may expect, this is the worse name you can give to your unit test
}
@Test
void testCalculateTotal(){
// This is too general and doesn't tell what is the expected behavior
// and under what conditions
}
Improved example
@Test
void calcluateTotal_Should_Return_Zero_When_No_Products(){
}
@Test
void Should_ThrowException_When_Max_Capacity_Reached(){
}
note
With JUnit, you can use the @DisplayName name annotation to provide a custom name or description for your tests.