Reader small image

You're reading from  How to Build Android Apps with Kotlin

Product typeBook
Published inFeb 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781838984113
Edition1st Edition
Languages
Right arrow
Authors (4):
Alex Forrester
Alex Forrester
author image
Alex Forrester

Alex Forrester is an experienced software developer with more than 20 years of experience in mobile, web development, and content management systems. He has been working with Android for over 8 years, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The Automobile Association, HSBC, The Discovery Channel, and O2. Alex lives in Hertfordshire with his wife and daughter. When he's not developing, he likes rugby and running in the Chiltern hills.
Read more about Alex Forrester

Eran Boudjnah
Eran Boudjnah
author image
Eran Boudjnah

Eran Boudjnah is a developer with over 20 years of experience in developing desktop applications, websites, interactive attractions, and mobile applications. He has been working with Android for about 7 years, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat) to large-scale companies (Sky) and conglomerates. He is passionate about board games (with a modest collection of a few hundred games) and has a Transformers collection he's quite proud of. Eran lives in North London with Lea, his wife.
Read more about Eran Boudjnah

Alexandru Dumbravan
Alexandru Dumbravan
author image
Alexandru Dumbravan

Alexandru Dumbravan has been an Android Developer since 2011 and worked across a variety of Android applications which contained features such as messaging, voice calls, file management, and location. He continues to broaden his development skills while working in London for a popular fintech company.
Read more about Alexandru Dumbravan

Jomar Tigcal
Jomar Tigcal
author image
Jomar Tigcal

Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He worked on various stages of app development for small startups to large companies. Jomar has also given talks and conducted training and workshops on Android. In his free time, he likes running and reading. He lives in Vancouver, Canada with his wife Celine.
Read more about Jomar Tigcal

View More author details
Right arrow

9. Unit Tests and Integration Tests with JUnit, Mockito, and Espresso

Overview

In this chapter, you will learn about testing on the Android platform and how to create unit tests, integration tests, and UI tests. You will see how to create each of these types of tests, analyze how it runs, and work with frameworks such as JUnit, Mockito, Robolectric, and Espresso. You will also learn about test-driven development, a software development practice that prioritizes tests over implementation. By the end of this chapter, you will be able to combine your new testing skills to work on a realistic project.

Introduction

In previous chapters, you learned about how to load background data and display it in the UI and how to set up API calls to retrieve data. But how can you be sure that things work well? What if you're in a situation where you have to fix a bug in a project that you haven't interacted much with in the past? How can you know that the fix you are applying won't trigger another bug? The answer to these questions is through tests.

In this chapter, we will analyze the types of tests developers can write and we will look at available testing tools to ease the testing experience. The first issue that arises is the fact that desktops or laptops, which have different operating systems, are used to develop mobile applications. This implies that the tests also have to be run on the device or emulator, which will slow the tests down. In order to solve this issue, we are presented with two types of tests: local tests, which are located in the test folder and...

JUnit

JUnit is a framework for writing unit tests both in Java and in Android. It is responsible for how tests are executed, allowing developers to configure their tests. It offers a multitude of features, such as the following:

  • Setup and teardown: These are called before and after each test method is executed, allowing developers to set up relevant data for the test and clear it once the test is executed. They are represented by the @Before and @After annotations.
  • Assertions: These are used to verify the result of an operation against an expected value.
  • Rules: These allow developers to set up inputs that are common for multiple tests.
  • Runners: Using these, you can specify how the tests can be executed.
  • Parameters: These allow a test method to be executed with multiple inputs.
  • Orderings: These specify in which order the tests should be executed.
  • Matchers: These allow you to define patterns that can then be used to validate the results of the...

Android Studio Testing Tips

Android Studio comes with a good set of shortcuts and visual tools to help with testing. If you want to create a new test for your class or go to existing tests for your class, you can use the Ctrl + Shift + T (Windows) or Command + Shift + T (Mac) shortcut. In order to run tests, there are multiple options: right-click your file or the package and select the Run Tests in... option, or if you want to run a test independently, you can go to the particular test method and select the green icon either to the top of the class, which will execute all the tests in the class; or, for an individual test, you can click the green icon next to the @Test annotated methods. This will trigger the test execution, which will be displayed in the Run tab, as shown in the following screenshot. When the tests are completed, they will become either red or green, depending on their success state:

Figure 9.2: Test output in Android Studio

Another important...

Mockito

In the preceding examples, we looked at how to set up a unit test and how to use assertions to verify the result of an operation. What if we want to verify whether a certain method was called? Or what if we want to manipulate the test input in order to test a specific scenario? In these types of situations, we can use Mockito. This is a library that helps developers set up dummy objects that can be injected into the objects under test and allows them to verify method calls, set up inputs, and even monitor the test objects themselves.

The library should be added to your test Gradle setup, as follows:

testImplementation 'org.mockito:mockito-core:3.6.0'

Now, let's look at the following code example (please note that, for brevity, import statements have been removed from the following code snippets):

class StringConcatenator(private val context: Context) {
    fun concatenate(@StringRes stringRes1: Int, 
     ...

Integration Tests

Let's assume your project is covered by unit tests where a lot of your logic is held. You now have to add these tested classes to an activity or a fragment and require them to update your UI. How can you be certain that these classes will work well with each other? The answer to that question is through integration testing. The idea behind this type of testing is to ensure that different components within your application integrate well with each other. Some examples include the following:

  • Ensuring that your API-related components parse the data well and interact well with your storage components.
  • The storage components are capable of storing and retrieving the data correctly.
  • The UI components load and display the appropriate data.
  • The transition between different screens in your application.

To aid with integration testing, the requirements are sometimes written in the format Given - When - Then. These usually represent acceptance...

UI Tests

UI tests are instrumented tests where developers can simulate user journeys and verify the interactions between different modules of the application. They are also referred to as end-to-end tests. For small applications, you can have one test suite, but for larger applications, you should split your test suites to cover particular user journeys (logging in, creating an account, setting up flows, and so on). Because they are executed on the device, you will need to write them in the androidTest package, which means they will run with the Instrumentation framework. Instrumentation works as follows:

  • The app is built and installed on the device.
  • A testing app will also be installed on the device that will monitor your app.
  • The testing app will execute the tests on your app and record the results.

One of the drawbacks of this is the fact that the tests will share persisted data, so if a test stores data on the device, then the second test can have access...

Test-Driven Development

Let's assume that you are tasked with building an activity that displays a calculator with the add, subtract, multiply, and divide options. You must also write tests for your implementation. Typically, you would build your UI and your activity and a separate Calculator class. Then, you would write the unit tests for your Calculator class and then your activity class.

Under the Android TDD process, you would have to write your UI test with your scenarios first. In order to achieve this, you can create a skeleton UI to avoid compile-time errors. After your UI test, you would need to write your Calculator test. Here, you would also need to create the necessary methods in the Calculator class to avoid compile-time errors.

If you run your tests in this phase, they would fail. This would force you to implement your code until the tests pass. Once your Calculator tests pass, you can connect your calculator to your UI until your UI tests pass. While this...

Summary

In this chapter, we looked at the different types of testing and the frameworks available for implementing these tests. We also took a look at the testing environment and how to structure it for each environment, as well as structuring your code in multiple components that can be individually unit tested. We analyzed different ways to test code, how we should approach testing, and how, by looking at different test results, we can improve our code. With TDD, we learned that by starting with testing, we can write our code faster and ensure it is less error-prone. The activity is where all these concepts came together into building a simple Android application, and we can observe how, by adding tests, the development time increases, but this pays off in the long term by eliminating possible bugs that appear when the code is modified.

The frameworks we have studied are some of the most common ones, but there are others that build on top of these and are used by developers in...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
How to Build Android Apps with Kotlin
Published in: Feb 2021Publisher: PacktISBN-13: 9781838984113
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Authors (4)

author image
Alex Forrester

Alex Forrester is an experienced software developer with more than 20 years of experience in mobile, web development, and content management systems. He has been working with Android for over 8 years, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The Automobile Association, HSBC, The Discovery Channel, and O2. Alex lives in Hertfordshire with his wife and daughter. When he's not developing, he likes rugby and running in the Chiltern hills.
Read more about Alex Forrester

author image
Eran Boudjnah

Eran Boudjnah is a developer with over 20 years of experience in developing desktop applications, websites, interactive attractions, and mobile applications. He has been working with Android for about 7 years, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat) to large-scale companies (Sky) and conglomerates. He is passionate about board games (with a modest collection of a few hundred games) and has a Transformers collection he's quite proud of. Eran lives in North London with Lea, his wife.
Read more about Eran Boudjnah

author image
Alexandru Dumbravan

Alexandru Dumbravan has been an Android Developer since 2011 and worked across a variety of Android applications which contained features such as messaging, voice calls, file management, and location. He continues to broaden his development skills while working in London for a popular fintech company.
Read more about Alexandru Dumbravan

author image
Jomar Tigcal

Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He worked on various stages of app development for small startups to large companies. Jomar has also given talks and conducted training and workshops on Android. In his free time, he likes running and reading. He lives in Vancouver, Canada with his wife Celine.
Read more about Jomar Tigcal