How to Test Your Android Code (Unit Testing Basics)

How to Test Your Android Code (Unit Testing Basics) How to Test Your Android Code (Unit Testing Basics)

Introduction: When you write code, you want to make sure it works correctly. But testing your app manually by clicking buttons on your screen takes a lot of time. If you change a function later, you have to test everything again. To solve this, developers write Unit Tests—simple, automated scripts that verify your code's calculations and logic in less than a second.

The Analogy: The Calculator Quality Inspector

Imagine you run a factory that makes physical calculators. You do not package and ship them to customers hoping they work. You hire a **Quality Inspector**.

The inspector follows three simple rules:

  • 1. Arrange: Grab a brand new calculator and turn it on.
  • 2. Act: Press the buttons 2 + 3 =.
  • 3. Assert: Look at the screen and verify if it displays exactly 5. If yes, the calculator passes. If it shows 6, it is rejected.

In coding, a Unit Test is that inspector. It runs a single function (a 'unit' of code) with specific inputs and checks if the output matches what you expect. This is called the AAA (Arrange, Act, Assert) pattern.

How to Write a Unit Test in Kotlin

Android projects use a built-in library called JUnit. Let's see how to write a simple test for a math helper class.

Step 1: Write the Class to be Tested

Suppose we have a simple TaxCalculator class that calculates tax based on a price:

kotlin
class TaxCalculator {
    fun calculateTax(price: Double): Double {
        return price * 0.15 // 15% tax rate
    }
}

Step 2: Write the Test Code

Inside your project's test/ folder, create a test class. We mark test functions with the @Test annotation, and use assertEquals() to check the results:

kotlin
import org.junit.Assert.assertEquals
import org.junit.Test

class TaxCalculatorTest {

    @Test
    fun testTaxCalculation_isCorrect() {
        // 1. ARRANGE: Set up the calculator
        val calculator = TaxCalculator()
        
        // 2. ACT: Calculate tax for $100
        val tax = calculator.calculateTax(100.0)
        
        // 3. ASSERT: Verify if tax is exactly $15.0
        // Syntax: assertEquals(expectedValue, actualValue, deltaAllowed)
        assertEquals(15.0, tax, 0.001)
    }
}
To run this test, click the green play arrow next to the function name in Android Studio. In less than a second, the console will show a green checkmark if correct, or a red cross if wrong!

Types of Android Tests

Android has two main testing folders. Learn the difference in this comparison table:

Test CategoryRuns OnExecution SpeedPurpose
Unit Tests (test/ folder)Your computer's CPU (JVM)🚀 Instant (under 1 second)Testing math logic, viewmodel states, network data mapping.
Instrumented UI Tests (androidTest/ folder)A real Android phone or simulator🐢 Slow (takes minutes to start)Testing UI flows, database writes, clicking buttons, screen swipes.
The 70-20-10 Testing Rule: Write 70% Unit Tests (fast and cheap), 20% integration tests (testing databases/APIs), and only 10% UI tests (slow and fragile). This keeps your development speed fast and your tests reliable!

Summary

Unit testing is writing small, automated scripts to verify that single functions output correct results. By following the Arrange-Act-Assert structure and using JUnit's assertEquals(), you can run thousands of tests instantly on your computer without running a phone simulator. Adopt testing to code with confidence and ship bug-free apps!

 All Articles
Share: