Write Tests for all your Missed Branches

Branch coverage is often overlooked while writing tests but if you have the knowledge of all the paths that your code can take, it will help you to understand all the edge cases. In this blog post, you will understand how to identify missing branches and write better tests for your code.
Let’s start with the basics.
What is branch coverage?
Branch coverage is a metric that indicates whether all branches in a codebase are exercised by tests. A “branch” is one of the possible execution paths the code can take after a decision statement — e.g., an if statement — gets evaluated.
Let’s start with a simple example, we have a method that executes something based on a if
condition
And if we decide to only write the following test for our method
The method will have 100% code coverage because all the lines of the method are executed while running the test but there is a missing branch, we haven’t added a test when the condition
is false
. If you add another test like the one below, you will be able to cover all the branches.
Now things become a little more interesting when our if
condition becomes a bit more complex
You might think if you add two tests like the ones below all the branches will be covered
But if you have seen the cover image of this blog, you will notice that there are actually 4 branches.
true && true
true && false
false && true
false && false
You can write the following tests for your code to achieve 100% branch coverage
Now let’s look at another example
In this example we are using the safe call operator (?.
). If we write one test to check the value of name
, we will miss out on the branch that can be null
. So whenever we use the safe call operator we should keep in mind that it will create two branches and both of them should be tested. Now since we know that, our test cases will look like this
Even if your tests have covered all the branches, you can always add more tests for your own understanding. In this blog post, I highlighted only the missing branches but a lot more tests can be written. I hope now you have a better understanding of all the paths/branches that your code can be executed in and you will think about these edge cases while writing unit tests.
If you have feedback, feel free to tweet/message me on Twitter.
Click 👏 to say “thanks!” and help others find this article.
To be up-to-date with great news on Kt. Academy, subscribe to the newsletter, observe Twitter and follow us on Medium.
If you need a Kotlin workshop, check how we can help you: kt.academy.
