Blog Infos
Author
Published
Topics
, , ,
Published

Hey there! If you’re diving into unit testing in Android, you’ve probably come across the term “mocking.” Maybe you’ve heard of libraries like Mockito, and now you’re wondering, “What’s this MockK thing?” Don’t worry, I’m here to walk you through the basics of mocking and show you why MockK is a powerful tool you should consider. Let’s keep this casual and fun, like we’re chatting over coffee!

What is Mocking?

First things first, let’s clarify what “mocking” is. When you’re writing unit tests, you want to test small, isolated pieces of code (functions or classes). But often, these pieces of code rely on other components or dependencies.

For example, imagine you’re testing a UserService class that calls an API. You don’t want to make actual API calls during your test—that would be slow and unreliable. Instead, you “mock” the API call by replacing it with a fake version that behaves the way you expect.

In short:

  • Mocking is creating fake versions of objects or functions to control their behavior in tests.
  • It helps you isolate what you’re testing and avoid dealing with real dependencies.
Example of Why You Need Mocks

Imagine you have this function:

fun fetchUser(): String {
    val apiResponse = apiService.getUserFromApi() // This makes a real API call
    return "Hello, ${apiResponse.name}"
}

 

To test this function properly, you don’t want to call apiService.getUserFromApi() for real. Instead, you’ll mock it to return a predefined response like this:

 

val mockApiResponse = User(name = "John Doe")

 

Now you can control what apiService.getUserFromApi() returns and test the fetchUser() function without worrying about the actual API.

Why Use MockK Over Other Libraries?

There are several mocking libraries out there, but MockK stands out, especially for Kotlin developers. Here’s why MockK is awesome:

  1. Designed for Kotlin: Unlike Mockito (which was built for Java and adapted for Kotlin), MockK was created with Kotlin in mind. This means it supports Kotlin features like final classes, extension functions, and coroutines out of the box.
  2. Simpler Syntax: MockK has a clean, easy-to-read syntax that makes your tests more readable.
  3. Powerful Features: MockK supports advanced features like mocking static methods, objects, and even constructors.
  4. Coroutines Support: If you’re working with coroutines, MockK makes it super easy to mock suspend functions.
A Quick Comparison

Here’s a quick comparison of MockK and Mockito when mocking a simple class.

Using Mockito:

val mockUserService = mock(UserService::class.java)
`when`(mockUserService.getUserName()).thenReturn("John")

 

Using MockK:

val mockUserService = mockk<UserService>()
every { mockUserService.getUserName() } returns "John"

 

See how MockK’s syntax is more Kotlin-friendly? Let’s dive into how to set it up in your project.

Setting Up MockK in Your Android Project

Adding MockK to your project is super easy. Here’s what you need to do:

Step 1: Add the Dependency

In your build.gradle (Module-level) file, add the MockK dependency:

dependencies {
    testImplementation "io.mockk:mockk:1.12.0"
}

 

If you’re testing Android components, add the Android-specific version of MockK:

dependencies {
    androidTestImplementation "io.mockk:mockk-android:1.12.0"
}

 

Step 2: Sync the Project

After adding the dependencies, sync your project to download MockK.

Basic MockK Syntax and Examples

Now that you’ve got MockK set up, let’s check out some basic examples to get you started!

1. Creating a Mock

To create a mock of a class or interface, use mockk():

val mockUserService = mockk<UserService>()

 

2. Stubbing a Method with every {}

Use every {} to define what a mocked method should return:

every { mockUserService.getUserName() } returns "John Doe"

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

, ,

Intro to unit testing coroutines with Kotest & MockK

In this workshop, you’ll learn how to test coroutines effectively using the Kotest and MockK libraries, ensuring your app handles concurrent tasks efficiently and with confidence.
Watch Video

Intro to unit testing coroutines with Kotest & MockK

Jaroslaw Michalik
Kotlin GDE

Intro to unit testing coroutines with Kotest & MockK

Jaroslaw Michalik
Kotlin GDE

Intro to unit testing coroutines with Kotest & MockK

Jaroslaw Michali ...
Kotlin GDE

Jobs

No results found.

3. Verifying Method Calls with verify {}

You can check if a method was called during the test using verify {}:

fetchUser() // Call the function that uses mockUserService
verify { mockUserService.getUserName() } // Verify the method was called

 

Full Example

Here’s a complete example combining everything:

class UserService {
    fun getUserName(): String = "Real User"
}
class UserGreeting(private val userService: UserService) {
    fun greetUser(): String {
        return "Hello, ${userService.getUserName()}"
    }
}
// In your test class
@Test
fun `test greetUser returns correct greeting`() {
    // Create a mock
    val mockUserService = mockk<UserService>()
    // Stub the method
    every { mockUserService.getUserName() } returns "John Doe"
    // Create the class under test
    val userGreeting = UserGreeting(mockUserService)
    // Call the function
    val result = userGreeting.greetUser()
    // Verify the result
    assertEquals("Hello, John Doe", result)
    // Verify the method call
    verify { mockUserService.getUserName() }
}

 

Conclusion

That’s it for the basics of MockK! You’ve learned what mocking is, why MockK is a great choice for Kotlin developers, how to set it up, and how to use basic functions like mockk()every {}, and verify {}.

In the next article, we’ll dive into some advanced MockK techniques like mocking static methods, final classes, and more. Stay tuned, and happy testing!

This article is previously published on proandroiddev.com.

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
Hi, today I come to you with a quick tip on how to update…
READ MORE
blog
Automation is a key point of Software Testing once it make possible to reproduce…
READ MORE
blog
Drag and Drop reordering in Recyclerview can be achieved with ItemTouchHelper (checkout implementation reference).…
READ MORE
Menu