Learn Unit Testing in Android by building a sample application

In the last article, I listed out the benefits of Unit Testing your applications. In this tutorial, we’ll take a look at how to begin Unit Testing your Android Applications.

If you haven’t checked out the previous article on why you should unit test your android app, then you must take a quick look at it before moving ahead with this one.

Let’s get started!!

Install the dependencies

Place these dependencies in your app level build.gradle file:

testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-core:1.10.19'
  • Junit: It is a “Unit Testing” framework for Java Applications. It is an automation framework for Unit as well as UI Testing. It contains annotations such as @Test, @Before, @After etc.
  • Mockito: Mockito mocks (or fakes) the dependencies required by the class being tested. It provides annotations such as @Mock.

Create a sample app:

**IMPORTANT**

Unit Tests are generally written before writing the actual application. But for the sake of explanation in this article, I am creating a sample app before writing Unit Tests.

Unit Testing is done to ensure that the developer would be unable to write low quality/erroneous code. It makes sense to write Unit Tests before writing the actual app as then you wouldn’t have a bias towards the success of your tests, you will write tests beforehand and the actual code will have to adhere to the design guidelines laid out by the test.

Now, lets create our sample app.

We’ll be creating a simple app, whose sole purpose would be to get user data from input fields and save it using in a shared preference file

Visit Now