DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. A New Mocking Tool for Kotlin

A New Mocking Tool for Kotlin

Take a look at MockK, a new mocking tool designed specifically for use with Kotlin code, helping you avoid cumbersome Java wrappers.

Oleksiy Pylypenko user avatar by
Oleksiy Pylypenko
·
Nov. 08, 17 · Tutorial
Like (14)
Save
Tweet
Share
17.28K Views

Join the DZone community and get the full member experience.

Join For Free

DinoOne pain point in testing Kotlin code is mocking. Have you ever tried to use a Mockito wrapper? It tries to hide this Java dinosaur in a DSL, but it still feels so unnatural and Java-ish

In this aMockKrticle, I'd like to present new shiny pure Kotlin mocking library — MockK. Its main philosophy is first-class support for Kotlin features. Thus, your code using coroutines or lambda blocks naturally fits into a simple DSL describing the behavior of objects.

Syntax

First, you need to create a mock or spy:

val mock = mockk<Type>()
val spy = spyk<Type>(Type(...))


Then, you can stub some calls with argument matchers or regular arguments:

every {
  mock.call(any(), eq(3), more(4))
} returns 5


Stubbed mocks can now be used in some tested code and called as regular objects.

mock.call(22, 3, 6) // returns 5


After testing is done, you can verify calls again with matchers or regular arguments:

verify {
    mock.call(22, 3, more(4))
}


That's it for the basics, but there is a lot more, like two dozen types of matchers, coroutine coEvery/coVerify, verification modes, etc. Check out the documentation here and examples here.

Features

Some things are very similar to Mockito, and that is inevitable. But it's not about features themselves — Mockito and PowerMock have tons of features. It's about making it look and feel like Kotlin code.

Let me describe few things that help write clean code.

1. Chained Call Mocking

For example, you are going to test some web-handling code. Like this one:

ctx.request.headers[HttpHeaders.Host]


This value is then used for building your request. To test it, you need a mocked ctx and to provide behavior for each of three method calls: getRequest, getHeaders, and get.

In MockK, you can simply write:

every { request.headers[HttpHeaders.Host] } returns "host"


And the chain of mocking calls is captured and stubbed. Similar to deep stubs, but better.

2. Partial Matcher Specification

Many things can be simply better just because we use Kotlin. One of them is the specification of parts of arguments as matchers. Yes, truly you can do it. Only in Kotlin! And it fits Kotlin very well. Why? Because there is such things as named and default parameters.

Let's get back to another example:

fun response(html: String = "",
    contentType: String = "text/html",
    charset: Charset = Charset.forName("UTF-8"),
    status: HttpResponseStatus = HttpResponseStatus.OK): HttpResponse


So this is a very simple function to build an HTTP response. In dinosaur wrappers, you need to specify all arguments as matchers or none of them. That's not the case with MockK

every {
    response(html = match {
        it.startsWith("<html>")
    }) 
} returns HttpResponse(...)


Or:

every { 
    response(html = any(),
           status = HttpResponseStatus.BadRequest)
} returns HttpResponse(...)


Or actually any combination of matchers and regular arguments.

The tricky thing is that it is just impossible to do that in Java. In Kotlin this block is a lambda, and it can be executed several times. And thus a library can randomize values and guess what matchers are placed at what argument positions. Regular arguments are always constants. Almost always. Actually, they are until the moment when a default value is some sophisticated function returning time, for example, or random value. In that case, you do need to manually override it via matcher. But come on, the idea is very cool, isn't it? You just need to deal with a few corner cases. Okay, one corner case. And as I said before, it is very natural to Kotlin.  

3. Matcher Expressions

The idea is simple. Just allow combining matchers into composite matchers. Partial argument specifications make it even more powerful. Additionally, you can create a matcher that extends CompositeMatcher and create your own expression langauge. 

fun sum(a: Int, b:Int): Int

every { 
    obj.sum(any(), any()) 
} returns 0

every {
    obj.sum(
        or(eq(3), more(5)), 
        less(4)
    ) 
} answers { firstArg<Int>() + secondArg<Int>() }

Image title


4. Coroutines

First-class support of coroutines as matchers and as stubbing/verification blocks:

// as stubbing block

suspend fun respond(message: Any)

coEvery {
    appCall.respond(any())
} just Runs

// both as matcher and as block

class HtmlContent {
   suspend fun writeTo(channel: WriteChannel)
}

val channel = ... some channel ...
coVerify {
    appCall.respond(coAny<HtmlContent> { content ->
        content.writeTo(channel)
    })
}


So you don't need to manually wrap all the calls in runBlocking or similar. Just works.

5. Lambdas

Very often, when mocking DSLs, you need to call lambdas. There are plenty of ways to do that, capturing or answering alike, but the simplest way is to just use the special invoke matcher and provide arguments.

class A {
    fun b(block: () -> Unit)
}

every {
   a.b(invoke(args())
} just Runs


6. Verification Modes

If you need some ordering or checking of a full sequence of calls, that is easily achievable:

verify { // unordered by default
    obj.sum(1, 2)
    obj.sum(1, 3)
    obj.sum(2, 2)
}

verifyOrder { // calls where ordered like that
    obj.sum(1, 2)
    obj.sum(1, 3)
    obj.sum(2, 2)
}

verifySequence { // this was the exact sequence of calls
    obj.sum(1, 2)
    obj.sum(1, 3)
    obj.sum(2, 2)
}


Conclusion

All these tiny details make writing a MockK DSL in Kotlin a natural fit. I bet the wrapper syntax is something that can never be so nice as a native implementation in regards to clean and concise code. Besides that, mocking wrappers do not have the possibilities for future maneuvers as an implementation from scratch has.

Good luck and please star my repo MockK. Thanks!

Kotlin (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Understanding and Solving the AWS Lambda Cold Start Problem
  • The Power of Zero-Knowledge Proofs: Exploring the New ConsenSys zkEVM
  • Steel Threads Are a Technique That Will Make You a Better Engineer
  • Tracking Software Architecture Decisions

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: