0
0
Kotlinprogramming~30 mins

Mocking with MockK in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Mocking with MockK
📖 Scenario: You are writing tests for a simple calculator app. You want to check how your code behaves when the calculator service returns specific results without calling the real service.
🎯 Goal: Learn how to use MockK to create a mock of a calculator service, configure its behavior, and verify the output of a function that uses this service.
📋 What You'll Learn
Create an interface called CalculatorService with a function add(a: Int, b: Int): Int
Create a mock of CalculatorService using MockK
Configure the mock to return a specific value when add is called with certain arguments
Call the add function on the mock and print the result
💡 Why This Matters
🌍 Real World
Mocking helps you test your code without relying on real services or complex dependencies. This makes tests faster and more reliable.
💼 Career
Many software development jobs require writing unit tests. Knowing how to use mocking libraries like MockK is essential for testing Kotlin applications effectively.
Progress0 / 4 steps
1
Create the CalculatorService interface
Create an interface called CalculatorService with a function add(a: Int, b: Int): Int.
Kotlin
Need a hint?

Use the interface keyword and define the add function with two Int parameters and an Int return type.

2
Create a mock of CalculatorService
Create a variable called mockCalculator and assign it a mock of CalculatorService using mockk().
Kotlin
Need a hint?

Use val mockCalculator = mockk<CalculatorService>() to create the mock.

3
Configure the mock behavior
Use every { mockCalculator.add(2, 3) } to return 5.
Kotlin
Need a hint?

Use every { mockCalculator.add(2, 3) } returns 5 to set the mock's return value.

4
Call the mock and print the result
Call mockCalculator.add(2, 3) and print the result using println.
Kotlin
Need a hint?

Call mockCalculator.add(2, 3), store it in result, then print result.