Naming Unit Tests

When it comes to naming the unit test methods, then technically we can give our unit test method any name we like. But as we work with different teams and developers, we will notice that many developers follow a specific naming convention to help them make test methods more descriptive. It is good to make the name of the test method descriptive and speak for itself. And the goal is to understand what the test method is going to test just by looking at the method name rather than by looking at the code it contains and trying to figure it out from the code.
Why do we need to follow a specific naming convention?
it’s obvious to figure out what a test method is doing by looking at its code when it’s simple. but when we’re reviewing test methods written by someone else and there are a lot more test methods in the class and there is much more code in the test method itself, naming of test method will be very helpful.
The disadvantage of this approach is names of test methods look very long in the test report. However, If you are testing java with a testing framework like JUnit we can use the @DisplayName annotation to make these names look shorter and less technical.
Pattern for naming the test methods
In this simple example, I’m going to show you the template that we’re going to follow and also the most commonly used naming convention pattern when developers write unit tests.
test<systemUnderTest>_<conditionOrStateChange>_<expectedResult>
- Application code to be tested:
public UserDto getUser(String email) {
UserEntity userEntity = usersRepository.findByEmail(email);
if (userEntity == null)
throw new UsernameNotFoundException(email);
UserDto returnValue = new UserDto();
BeanUtils.copyProperties(userEntity, returnValue);
return returnValue;
}
- A test method that tests the above application code that follows the naming convention:
@Test
void testGetUser_WhenEmailProvided_ShouldReturnsUserDtoObject() {
//Arrange (Given) //Act (When) //Assert (Then)
}
Thank you for staying until the end of this article. If you enjoyed reading it, please press that clap👏 a few times, leave a comment and please share if you think this article will help someone else as well.
If you’re interested in more articles like this, Follow me on Medium!