unit testing

Intorduction to Unit Testing – Why should you start writing unit tests

Unit Testing is one of the hottest topics in Agile methodology along with other things such as Integration Testing, CI, CD etc. And rightly so!!

 

So, what is Unit Testing?

According to Wikipedia, Unit Testing is a software testing method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine whether they are fit for use.

In other words, it is a piece of code that is written to test some other code, such as the code of presenter layer in Model-View-Presenter pattern.

A code is passed on for integration testing if and only if it passes all its unit test cases. When the code passes all its test cases, it is said to be complete. As a result, unit testing provides a lot of benefits such as finding software bugs early, easier refactoring of old code and a source of documentation.

Unit testing tests the smallest piece of “isolatable” code and tests that whether it is working correctly by passing it through some test cases. During unit testing, all of the dependencies of that part of code are provided by some mocking framework such as Mockito.

 

When is a code Unit Testable?

Not all of the code can be unit tested. A piece of code can be unit tested if and only if its dependencies are being provided by dependency injection, or can be mocked by a mocking framework.

For example, take a look at this:

public String doSomething(Date someDate){
    Date date = new Date();

    if(date.isAfter(someDate)){
        return "tomorrow";
    }else if(date.isBefore(someDate)){
        return "Yesterday";
    }else{
        return "Equal";
    }

}

This explanation is as simple as it can get.

We are creating a new instance of Date object which will give us today’s date. We are comparing today’s date with some another date object “someDate”.

This behavior is non-deterministic. Each instance of running of this code will give a new date object for today. Hence it is not possible to write unit tests for this code.

Now have a look at this:

public String doSomething(Date source, Date someDate){
    if(source.isAfter(someDate)){
        return "Tomorrow";
    }else if(source.isBefore(someDate)){
        return "Yesterday";
    }else{
        return "Equal";
    }
}

This is what an example unit test for this method would look like:

@Test
public void comparing7thwith10th_returnsyesterday() throws Exception {
    try{
        Date date = new date();
        asserEquals(doSomething(new Date(),new Date()),"Equal");
    }catch(Exception e){

    }
}

It is not a good practice to instantiate every dependency in the class itself. Dependencies should be provided externally to the class hence making the class more testable. That is why the concept of Dependency Injection is in trend these days.

 

Benefits of Unit Testing

Unit Testing has many benefits such as finding software bugs early, simplifying refactoring, simplifying integration, providing documentation etc. We’ll look into them in more detail now:

 

Follows agile methodology

When you begin adding more and more features to your app, you may need to change the old code. But changing the old code is risky as well as costly. You may end up breaking the old functionality and then spend time again finding the bug and fixing the errors.

This is a tedious process and can be costly to the company.

If Unit Tests are already in place, there is no way to break the old functionality (unless you determined to do so XD). If there is an error in some part of your code, you’ll know as soon as you run your Unit Tests. It is kind of a self-policing method which will save you a lot of headache in the long run. Unit Tests should be written before writing the remainder of the code.

 

Quality of code

Writing unit tests makes you think hard about the things such as architecture and design pattern of your code. As a result, you end up writing quality code which is elegant, easier to read and most importantly easier to refactor in the future.

This is the main goal of all the architectural and design patterns. To make the code more modular and testable.

 

Finding Bugs Early

Unit Testing is carried out before integrating it with the main code. So, if your code has some unexpected behavior, it can be spotted before mixing it with the old code. This prevents a lot of headache later on when you have integrated your code with the main working code.

It makes the process of integration and integration testing, a lot easier.

 

Provides Documentation

Unit Testing can provide documentation for your code. Developers who want to learn what a piece of code does can have a look at the unit tests to gain a basic understanding of the unit’s working.

 

Debugging Process

Unit Testing ensures less bugs and makes debugging easier. You must run unit tests constantly to make sure no test case is failing.

If a test case fails, then there is some problem with your existing code and it needs another look.

 

Gives you an edge above others

Writing unit tests is no joke!! It is a tedious task and requires more effort (atleast in my case) than the actual code itself. It makes you think. But it makes you much more productive in the long term.

Abraham Lincoln was quoted as saying “ Give me six hours to chop down a tree and I will spend the first four sharpening the ax.”

According to a survey, there is a shortage of quality/skilled software engineers in the industry, even though thousands of engineers are produced every year. The shortage is not the quantity, but the quality.

I myself know many people in my college who cannot write a simple “hello world” program and call themselves software engineers. They end up taking all kinds of jobs but software engineering.

So, if you want to be a good software engineer and work in your core field, having the invaluable skill of Unit Testing will give you a competitive advantage over your peers.

It will make your resume stand out from others and eventually increase your chances of landing that job. Trust me, learning how to unit test is worth the pain.

 

Reduces cost

Bugs can be found early in the development phase before integrating the code. It is really difficult to find the bugs later on in the whole codebase, more so if your codebase is really large. Bugs detected later on are the result of a lot of changes and you don’t know which one.

Finding bugs later on leads to more development time and eventually, increased costs.

 

Unit Testing in Android

Unit Testing is not specific to any platform. It exists for all languages and platforms, but since it is an Android Development Blog, let’s talk about android.

Android Testing Support Library (ATSL) provides a great framework for testing your app. It has Junit 4 – compatible test runner (AndroidJUnitRunner) and functional UI testing through Espresso and UI Automator.

These tests can be run directly in Android Studio IDE or from the command line.

 

So, what’s next?

In the next article, we’ll learn how to write Unit Test for android applications and how to run them on Android Studio.

So, if you are someone who’s just beginning with Unit Testing in Android Development you would not want to miss out on the next article. Stay tuned!!

 

Like what you read ? Don’t forget to share this post on FacebookWhatsapp and LinkedIn.

You can follow me on LinkedInQuoraTwitter and Instagram where I answer questions related to Mobile Development, especially Android and Flutter.

 

 

 

About the author

shares