How to Do Unit Testing in Kotlin Like a Google Engineer

Table of Contents

Unit testing in Kotlin isn’t just about making sure your code works. It’s about writing tests that prove your code works, stays reliable over time, and catches bugs before they hit production. Google engineers treat testing as a core development skill, not an afterthought. And you can do the same.

In this guide, we’ll break down unit testing in Kotlin in a simple way. We’ll show you how to write clean, maintainable tests just like a pro. Whether you’re building Android apps or server-side Kotlin applications, this blog will give you the confidence to write bulletproof unit tests.

What is Unit Testing in Kotlin?

Unit testing is the process of testing individual units of code (like functions or classes) in isolation to ensure they work as expected. Unlike integration or UI tests, unit tests focus on your own logic, not external libraries or frameworks.

Unit Test is a piece of code that is not a part of your application. It can create and call all of your application’s public classes and methods… You want to verify whether application code works as you expect.

Why Google Engineers Prioritize Unit Testing

  • Fast feedback: Tests run in milliseconds. You catch bugs fast.
  • Safe refactoring: When you change code, tests confirm nothing breaks.
  • Confidence in deployment: You ship faster because you trust your code.
  • Documents behavior: Tests show how code is supposed to work.

Now let’s get to the fun part — how to actually do this in Kotlin.

Setting Up Unit Testing in Kotlin

Most Kotlin projects use JUnit as the test framework. Android Studio and IntelliJ IDEA make setup easy:

1. Add JUnit to your project dependencies (usually already included in Android projects). Use JUnit5 for unit testing in Kotlin. It’s modern, fast, and integrates well.

Kotlin
dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter:5.10.0")
    testImplementation("org.jetbrains.kotlin:kotlin-test:1.9.0")
}

test {
    useJUnitPlatform()
}

2. Create a test class for the code you want to test.

3. Write test methods using the @Test annotation.

Basic Unit Test in Kotlin

Let’s say you have a function that adds two numbers:

Kotlin
fun add(a: Int, b: Int): Int = a + b

Here’s how you write a test for it:

Kotlin
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test

class MathUtilsTest {
    @Test
    fun `add should return sum of two numbers`() {
        val result = add(3, 4)
        assertEquals(7, result)
    }
}

What’s happening here?

  • @Test marks the method as a test case.
  • assertEquals checks the expected and actual values.
  • The function name is written in backticks for clarity.

Best Practices for Unit Testing in Kotlin

Google engineers follow these principles to ensure effective unit testing in Kotlin:

1. Keep Tests Small and Focused

Each test should verify one behavior or scenario. This makes tests easy to read and maintain.

2. Use Immutable Test Data

Initialize objects as val and avoid mutating shared state between tests. This prevents flaky tests and makes debugging easier.

3. Leverage Kotlin Features

Kotlin’s concise syntax (like data classes and extension functions) makes tests more readable and expressive.

4. Test Lifecycle Annotations

  • @Before: Setup code before each test.
  • @After: Cleanup after each test.
  • @TestInstance(Lifecycle.PER_CLASS): Reuse test class instance for all tests (avoids static members).

5. Mock Dependencies

Use libraries like MockK or Mockito to replace dependencies with mock objects, so you only test your own code’s logic.

Testing with Mocks in Kotlin

Sometimes, your code depends on external systems (like APIs or databases). For true unit testing in Kotlin, you should mock those dependencies.

Use MockK — a Kotlin-first mocking library.

Add MockK to Your Project

Kotlin
dependencies {
    testImplementation("io.mockk:mockk:1.13.8")
}

Example with MockK

Kotlin
interface UserRepository {
    fun getUser(id: Int): String
}

class UserService(private val repository: UserRepository) {
    fun getUsername(id: Int): String = repository.getUser(id).uppercase()
}

class UserServiceTest {
    private val repository = mockk<UserRepository>()
    private val service = UserService(repository)
    @Test
    fun `getUsername returns uppercased username`() {
        every { repository.getUser(1) } returns "amol"
        val result = service.getUsername(1)
        assertEquals("AMOL", result)
    }
}

Key Points

  • mockk<UserRepository>() creates a mock object.
  • every { ... } returns ... defines behavior for the mock.
  • Test checks the result of the service method in isolation.

Testing Coroutines in Kotlin

Kotlin’s coroutines make asynchronous code easier, but they require special handling in tests.

Example: Testing a Coroutine Function

Suppose you have:

Kotlin
suspend fun fetchData(): String {
    delay(1000) // Simulate network call
    return "Data"
}

Test with runBlocking:

Kotlin
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.junit.Assert.assertEquals

class DataFetchTest {
    @Test
    fun fetchDataReturnsCorrectValue() = runBlocking {
        val result = fetchData()
        assertEquals("Data", result)
    }
}

Tips:

  • Use runBlocking to execute suspending functions in tests.
  • For more advanced coroutine testing, use CoroutineTestRule and TestCoroutineDispatcher to control coroutine execution and skip delays.

Running and Maintaining Tests

  • Run tests frequently: Use your IDE or command line to run all tests after every change.
  • Fix failing tests immediately: Don’t ignore red tests.
  • Refactor tests as needed: Keep them clean and up-to-date as your code evolves.

Tips for Writing Great Unit Tests

  1. Name tests clearly: Describe what the test checks.
  2. Test one thing at a time: Keep tests focused.
  3. Keep tests fast: No real network/database.
  4. Avoid logic in tests: Use literal values.
  5. Use setup methods for repetitive boilerplate.

Common Mistakes to Avoid

  • Testing too much in one test
  • Using real APIs in unit tests
  • Not asserting outcomes
  • Ignoring failed tests
  • Skipping tests because “it works on my machine

Conclusion

Unit Testing in Kotlin isn’t just for Google engineers — it’s a superpower for every developer. By writing small, focused tests, leveraging Kotlin’s features, and using the right tools, you’ll catch bugs early and build robust applications with confidence. 

Start small, keep practicing, and soon unit testing will be second nature..!

Skill Up: Software & AI Updates!

Receive our latest insights and updates directly to your inbox

Related Posts

error: Content is protected !!