Cover the maximum you can

Coverage is the measurement of how much production code is covered by unit tests. The most common types of code coverage are line coverage and branch coverage.

Line coverage refers to how many statements are covered by the tests; a statement is usually one line of code (excluding comments). High line coverage means that more production code is executed during the tests, which means that chances of having undetected bugs are low.

Branch coverage on the other hand refers to how many different branches (paths) are executed by your tests. Branches are usually created using conditional statements (if, for, while etc). A test case that covers 100% of lines (which is hard to achieve ) does not necessarily cover 100% of the branches.

Consider the following method :

public String getPersonName(boolean isStudent) {
Person person = null;
if (isStudent) {
person = new Person();
}
return person.getName();
}

The following test case calls the method with the parameter true and covers all the lines of the function getPersonName(). Is this good enough?

The answer is no. Why? The branch coverage of that test is only 50% because if you call the method with the parameter false you will get a NullPointerException, so you need to add another test case to increase branch coverage.

@Test
void getPersonName_Returns_A_Name_when_Person_IsStudent(){
assertNotNull(getPersonName(true));
}

Many open source and commercial code coverage tools exist for many programming languages (ie: SonarQube). These tools can be integrated with build tools and can be defined as steps of CI/CD process.

Leave a Reply

Your email address will not be published. Required fields are marked *