Professional Documents
Culture Documents
Mocking Is Not Rocket Science: Basics: Oleksiy Pylypenko Follow Jan 10, 2018
Mocking Is Not Rocket Science: Basics: Oleksiy Pylypenko Follow Jan 10, 2018
Oleksiy Pylypenko
Follow
Jan 10, 2018 · 3 min read
Mocking is a technique to make testing code readable and maintainable. In three consequent
articles, I would like to show basics, features, and quirks of the MockK library. It is a new open
source library (github repository) focused on making mocking in Kotlin great.
Technique used in this article is stubbing, not mocking. This are two similar and often confused
terms. Read more about it here.
The main point to have stubs or mocks is to isolate testing one component, which is called
System Under Test, from their Dependent-On Components.
The System Under Test (SUT) refers to a system that is being tested for correct operation.
The basic idea is to wire SUT to mocked components instead of a Dependent-On Component.
Visualization of System Under Test with two mocked Depended On Component
Or in Kotlin:
class SystemUnderTest(
val dependency1: Dependency1,
val dependency2: Dependency2
)
fun calculate() =
dependency1.value1 + dependency2.value2.toInt()
@Test
fun calculateAddsValues() {
val doc1 = mockk<Dependency1>()
val doc2 = mockk<Dependency2>()
Creates a mock object with type Dependency1. This object is a replacement for first
Depdendent-On Component of a SUT.
Provides expected behavior for getter of value1 property. This means we expect that when
getter is called the value returned is 5.
The same for doc2 dependency. We expect value2 to return string “6”.
assertEquals(11, sut.calculate())
While executing calculate function, mocked components are called and expected behaviors are
executed. After that, we verify that result of executing a function with dependencies is correct.
Why is this valuable? In this simplified example, it is not so obvious. After all just providing
dependent components would test our SUT as well: