whatsapp_btn
whatsapp_btn Chat With Us

Home >> Android >> How to do Unit Testing Using Mockito in Android

How to do Unit Testing Using Mockito in Android

  8 min read
How to do Unit Testing Using Mockito in Android

Quick Summary

Unit Testing Using Mockito in Android, facilitated by Mockito, is crucial for ensuring code reliability. Beginning with setting up Mockito dependencies in the project’s build. gradle file, the process involves writing comprehensive test classes for targeted components like activities or presenters. Mockito’s functionality shines through in mocking dependencies, enabling isolated testing of components. Stubbing method calls aid in simulating various scenarios, while Mockito’s verification capabilities ensure method calls are as expected. Handling asynchronous operations, inherent in Android development, is simplified with Mockito’s support. Ultimately, executing tests via Android Studio’s test runner or Gradle validates code correctness, enhancing the overall robustness of Android applications.

What is Unit Testing?

In today’s world, as mobile applications grow more intricate, it’s vital to subject them to thorough testing to catch any potential bugs early on. Unfortunately, this crucial step is sometimes overlooked or sidelined by developers! To ensure that our code is easily testable, it’s essential to employ robust architectures like MVP or MVVM, which help maintain organization within our Android projects.

When it comes to testing, there are three primary categories to consider integrating into our testing arsenal:

1. UI Tests: These tests focus on verifying the functionality of our app’s user interface elements, such as buttons and screens. Typically, tools like Espresso are employed for this purpose.

2. Instrumented Tests: These tests run on real Android devices or emulators to validate that the app behaves correctly when users interact with it. Commonly used tools include AndroidX Test and Espresso.

3. Unit Tests: These tests are the backbone of our testing strategy, as they meticulously examine individual components of our code to ensure their proper functioning. For unit testing, developers often turn to tools like JUnit, Mockito, or Hamcrest.

The ultimate aim of Unit Testing is to catch and rectify bugs at an early stage, preventing them from escalating into significant issues down the line. In this tutorial, we’ll explore the world of Mockito in Android and uncover effective strategies for leveraging it to test our Android applications with precision.

What do you mean by Mockito?

Mockito, an essential tool for Android App Performance Optimization, empowers software developers to rigorously test their code. Picture building a complex Lego model, verifying individual pieces without assembling the entire structure. Mockito enables the creation of simulated components, mimicking real objects for isolated testing. Simplifying code evaluation, these mock objects ensure controlled testing, facilitating the assessment of code integration without complete assembly

Example: Let’s say you’re writing an app that checks the weather. Instead of actually connecting to a live weather service every time you test your app, you can use Mockito to create a fake weather service that provides pre-defined responses. This way, you can test how your app handles different weather scenarios quickly and easily.

Why Use Mockito?

Often, our classes rely on other classes and their methods. When we unit tests these classes, we aim to keep our tests independent of these dependencies. To achieve this, we use Mockito to create mock versions of the dependency classes, allowing us to focus on testing the main class. This level of isolation isn’t possible with JUnit alone.

Steps for Unit Testing Using Mockito

(Write an example of computations like addition, subtraction, etc to understand the Mockito framework)

Let’s explore a simple example of computations, such as addition and subtraction, to understand how to use the Mockito framework.

### Creating the Computation Classes

We’ll start by creating a file named `ComputationActivity.kt` to display all computations. For managing these operations, we’ll create an `Operations` class in `Operations.kt`. This `Operations` object will be passed as a parameter to the `ComputationActivity` class in its primary constructor.


#### ComputationActivity.kt

```kotlin

class ComputationActivity(private val operators: Operations) {

    fun getAddition(x: Int, y: Int): Int = operators.add(x, y)

    fun getSubtraction(x: Int, y: Int): Int = operators.subtract(x, y)

    fun getMultiplication(x: Int, y: Int): Int = operators.multiply(x, y)

    fun getDivision(x: Int, y: Int): Int = operators.divide(x, y)

}

```


#### Operations.kt

```kotlin

object Operations {

    fun add(x: Int, y: Int): Int = x + y

    fun subtract(x: Int, y: Int): Int = x - y

    fun multiply(x: Int, y: Int): Int = x * y

    fun divide(x: Int, y: Int): Int = x / y

}

```

### Adding Mockito Dependencies

To use Mockito in your project, include the following dependencies in your `build.gradle` file:


```groovy

testImplementation 'junit:junit:4.13.2'

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

testImplementation 'org.mockito:mockito-inline:2.13.0'

```

### Folder Structure for Tests

Place your test files in the `module-name/src/test` directory. This is where local unit tests are typically stored.

### Writing the Tests

Now, let’s add some test functions to our `ComputationTest.kt` file.

1. **MockitoJUnitRunner**: Use the `@RunWith` annotation with `MockitoJUnitRunner::class` to run the tests.

2. **@Mock**: Use the `@Mock` annotation to create mock objects. We will mock the `Operations` class because `ComputationActivity` depends on it.

3. **@Before**: Methods annotated with `@Before` run before each test to set up the test environment.

4. **@Test**: Use this annotation to define test functions.


#### ComputationTest.kt

```kotlin

@RunWith(MockitoJUnitRunner::class)

class ComputationTest {

    @Mock

    lateinit var operators: Operations

    lateinit var computationActivity: ComputationActivity

    @Before

    fun setUp() {

        computationActivity = ComputationActivity(operators)

    }

    @Test

    fun givenValidInput_getAddition_shouldCallAddOperator() {

        val x = 5

        val y = 10

        computationActivity.getAddition(x, y)

        verify(operators).add(x, y)

    }

}

```

The `verify` method checks whether a specific method of a mock object has been called.


### Additional Annotations

- **@After**: Executes after each test case completes.

- **@BeforeClass**: Runs once before all tests to set up resources that are expensive to initialize.

- **@AfterClass**: Runs once after all tests to clean up resources.

### Testing Final Classes

Mockito cannot directly test final or static classes, and Kotlin classes are final by default. To test these classes, you need the `mockito-inline` dependency. 

Mockito 2.25.0 introduced support for developers using `mockito-inline`, which is crucial for testing Kotlin classes. This concludes our tutorial on unit testing using Mockito in Android. Now, you can run the tests to ensure everything works correctly.

Running the Tests

To run all tests, right-click on the `ComputationTest.kt` file and select `Run`.

To run a specific test function, right-click on the desired function and select `Run`.

Conclusion

Mockito is a popular framework used by Android mobile developers to write unit tests, including testing final classes in Kotlin. This overview covered how to use Mockito for unit testing in Android applications. If you have any questions or suggestions, feel free to reach out to us—we’re here to help!

FAQ’S

Mockito makes your Android unit tests more reliable by helping you separate the component you're testing from its dependencies. With Mockito, you can create mock objects that pretend to be real dependencies. This lets you control and predict how your code behaves in different situations. By doing this, you can catch and fix problems early on in your development process, making your code stronger and easier to manage.

Using Mockito for isolating dependencies in Android unit tests brings several benefits. It helps make your tests more focused and easier to predict. Additionally, it improves your test coverage, making sure you're testing all the important parts of your code. Mockito also makes your code easier to maintain by keeping tests organized and readable. Plus, it helps you catch and fix problems early on in your development process.

Yes, Mockito plays well with other testing frameworks in Android development. It's commonly used alongside JUnit, which is the go-to testing framework for Java. This combination allows you to write and run unit tests seamlessly. Moreover, Mockito can also be paired with Android-specific testing frameworks like Espresso for UI testing and Robolectric for testing Android components independently. This flexibility makes it easy to adapt Mockito to your specific testing needs in Android development.

Hiring our developer can significantly elevate your Android project's testing strategy by implementing best practices in unit testing using Mockito. They bring a wealth of knowledge in designing efficient test cases that cover various scenarios, reducing the risk of overlooked bugs. Their proficiency with Mockito allows them to mock dependencies seamlessly, making your tests more focused and effective. With their skills, you can achieve higher test coverage, faster development cycles, and a more robust and reliable application.

Tagline Infotech
Tagline Infotech a well-known provider of IT services, is deeply committed to assisting other IT professionals in all facets of the industry. We continuously provide comprehensive and high-quality content and products that give customers a strategic edge and assist them in improving, expanding, and taking their business to new heights by using the power of technology. You may also find us on LinkedIn, Instagram, Facebook and Twitter.

Related Posts :

contact-us-bg

Our Global Presence

India

Surat (HQ)

Digital Valley, 423, Apple Square, beside Lajamni Chowk, Mota Varachha, Surat, Gujarat 394101

Ahmedabad

D-401, titanium city center, 100 feet anand nagar road, Ahmedabad-380015

 +91 9913 808 285

U.S.A

1133 Sampley Ln Leander, Texas, 78641

United Kingdom

52 Godalming Avenue, wallington, London - SM6 8NW

U.A.E

Office No - 43-44, Al Fahidi, Bur Dubai, Dubai, United Arab Emirates

 +971 58 569 4786