Android Unit Testing —Choosing Naming Convention and Test Cases | by Haitham Ayyash | Feb, 2022

Build bug-free Android apps

Photo by Guido Coppa on Unsplash

One of the most popular guidelines that make code clean is to choose a good name for methods and variables. you can follow these tips to choose a good name for test methods for your project:

Readability

Readability is achieved by choosing a simple, expressive, and meaningful name.

One Naming Convention

It’s better to use one naming convention across your project, which makes reading test reports more understandable and consistent.

MethodName_StateUnderTest_ExpectedBehavior

There are a lot of naming conventions, following some of them:

  • MethodName_ExpectedBehavior_StateUnderTest — example: getPost_postShouldCached_success
  • Should_ExpectedBehavior_When_StateUnderTest — example: should_throwException_when_NetworkError
  • When_StateUnderTest_Expect_ExpectedBehavior — example: when_serverError_expect_postNotCached

Some modern languages ​​like Kotlin, allow writing test methods with spaces.

We cannot test all possible cases since that would be infinite! Instead, we divide input/argument of the function being tested into categories and boundaries based on our case then pick a value from each category and boundary and test them.

Example #1: String Duplicator

Suppose we have StringDuplicator class that has a duplicateString method as the following

Example #2: Conflict Meetings Detector

Suppose we have ConflictMeetingsDetector that has haveMeetingsConflict method as the following:

Unit testing is just as important as production code. You should keep your test code as clean as possible to be able to maintain it, so unit tests will help you, otherwise, the unit tests will make your code complex and hard to maintain.

Leave a Comment