{"id":13427873,"url":"https://github.com/mockk/mockk","last_synced_at":"2025-05-14T11:04:03.954Z","repository":{"id":37451111,"uuid":"107331132","full_name":"mockk/mockk","owner":"mockk","description":"mocking library for Kotlin","archived":false,"fork":false,"pushed_at":"2025-04-11T22:00:20.000Z","size":14428,"stargazers_count":5542,"open_issues_count":304,"forks_count":364,"subscribers_count":57,"default_branch":"master","last_synced_at":"2025-04-22T05:36:30.618Z","etag":null,"topics":["argument-matchers","chain-calls","hacktoberfest","kotlin","matcher","mock","mocking-framework","tdd","testing","verification"],"latest_commit_sha":null,"homepage":"https://mockk.io","language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mockk.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"open_collective":"mockk"}},"created_at":"2017-10-17T22:31:23.000Z","updated_at":"2025-04-21T13:00:47.000Z","dependencies_parsed_at":"2023-02-18T07:31:20.454Z","dependency_job_id":"957a15f3-b812-4341-aa1c-91aa60330950","html_url":"https://github.com/mockk/mockk","commit_stats":{"total_commits":2121,"total_committers":159,"mean_commits":"13.339622641509434","dds":"0.38425271098538427","last_synced_commit":"79abc96d3235710d61beaf677ea1349ba12eea0c"},"previous_names":["oleksiyp/mockk"],"tags_count":99,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mockk%2Fmockk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mockk%2Fmockk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mockk%2Fmockk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mockk%2Fmockk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mockk","download_url":"https://codeload.github.com/mockk/mockk/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250251219,"owners_count":21399783,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["argument-matchers","chain-calls","hacktoberfest","kotlin","matcher","mock","mocking-framework","tdd","testing","verification"],"created_at":"2024-07-31T01:00:41.767Z","updated_at":"2025-04-22T13:46:02.312Z","avatar_url":"https://github.com/mockk.png","language":"Kotlin","readme":"\u003cdiv align=\"center\"\u003e\n    \u003cimg src=\"doc/logo-site.png\" width=\"400\" align=\"center\" alt=\"drawing\"/\u003e\n    \u003cimg src=\"doc/kotlin-logo.svg\" width=\"400\" align=\"center\" alt=\"drawing\"/\u003e\n\u003c/div\u003e\n\n[![Relase Version](https://img.shields.io/maven-central/v/io.mockk/mockk.svg?label=release)](https://search.maven.org/#search%7Cga%7C1%7Cmockk)\n[![Change log](https://img.shields.io/badge/change%20log-%E2%96%A4-yellow.svg)](https://github.com/mockk/mockk/releases)\n[![codecov](https://codecov.io/gh/mockk/mockk/branch/master/graph/badge.svg)](https://codecov.io/gh/mockk/mockk) \n[![Android](https://img.shields.io/badge/android-support-green.svg)](https://mockk.io/ANDROID)\n[![Matrix tests](https://img.shields.io/badge/matrix-test-e53994.svg)](https://mockk.io/MATRIX)\n[![Open Source Helpers](https://www.codetriage.com/mockk/mockk/badges/users.svg)](https://www.codetriage.com/mockk/mockk)\n\n## Getting started\n\nAll you need to get started is just to add a dependency to `MockK` library.\n\n#### Gradle/Maven dependency\n\n\u003ctable\u003e\n\u003cthead\u003e\u003ctr\u003e\u003cth\u003eApproach\u003c/th\u003e\u003cth\u003eInstruction\u003c/th\u003e\u003c/tr\u003e\u003c/thead\u003e\n\u003ctr\u003e\n\u003ctd\u003e\u003cimg src=\"doc/gradle.png\" alt=\"Gradle\"/\u003e\u003c/td\u003e\n\u003ctd\u003e\n\u003cpre\u003e\ntestImplementation \"io.mockk:mockk:${mockkVersion}\"\n\u003c/pre\u003e\n\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e\u003cimg src=\"doc/gradle.png\" alt=\"Gradle\"/\u003e (Kotlin DSL)\u003c/td\u003e\n \u003ctd\u003e\n  \u003cpre\u003etestImplementation(\"io.mockk:mockk:${mockkVersion}\")\u003c/pre\u003e\n \u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e\u003cimg src=\"doc/maven.png\" alt=\"Maven\"/\u003e\u003c/td\u003e\n\u003ctd\u003e\n\u003cpre\u003e\n \u0026lt;dependency\u0026gt;\n     \u0026lt;groupId\u0026gt;io.mockk\u0026lt;/groupId\u0026gt;\n     \u0026lt;artifactId\u0026gt;mockk-jvm\u0026lt;/artifactId\u0026gt;\n     \u0026lt;version\u0026gt;${mockkVersion}\u0026lt;/version\u0026gt;\n     \u0026lt;scope\u0026gt;test\u0026lt;/scope\u0026gt;\n \u0026lt;/dependency\u0026gt;\n\u003c/pre\u003e\n\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e\u003ca href=\"ANDROID.html\"\u003e\u003cimg align=\"top\" src=\"doc/robot-small.png\" height=\"20\" alt=\"android\"/\u003e Unit\u003c/a\u003e\u003c/td\u003e\n\u003ctd\u003e\n\u003cpre\u003e\ntestImplementation \"io.mockk:mockk-android:${mockkVersion}\"\ntestImplementation \"io.mockk:mockk-agent:${mockkVersion}\"\n\u003c/pre\u003e\n\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e\u003ca href=\"ANDROID.html\"\u003e\u003cimg align=\"top\" src=\"doc/robot-small.png\" height=\"20\" alt=\"android\"/\u003e Instrumented\u003c/a\u003e\u003c/td\u003e\n\u003ctd\u003e\n\u003cpre\u003e\nandroidTestImplementation \"io.mockk:mockk-android:${mockkVersion}\"\nandroidTestImplementation \"io.mockk:mockk-agent:${mockkVersion}\"\n\u003c/pre\u003e\n\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\n## DSL examples\n\nSimplest example. By default mocks are strict, so you need to provide some behaviour.\n\n```kotlin\nval car = mockk\u003cCar\u003e()\n\nevery { car.drive(Direction.NORTH) } returns Outcome.OK\n\ncar.drive(Direction.NORTH) // returns OK\n\nverify { car.drive(Direction.NORTH) }\n\nconfirmVerified(car)\n```\n\nSee the \"Features\" section below for more detailed examples.\n\n### Spring support\n\n * [springmockk](https://github.com/Ninja-Squad/springmockk) introduced in official [Spring Boot Kotlin tutorial](https://spring.io/guides/tutorials/spring-boot-kotlin/)\n\n### Quarkus support\n\n * [quarkus-mockk](https://github.com/quarkiverse/quarkus-mockk) adds support for mocking beans in Quarkus. Documentation can be found [here](https://quarkiverse.github.io/quarkiverse-docs/quarkus-mockk/dev/index.html)\n\n### Kotlin version support\n\nFrom version 1.13.0 MockK supports Kotlin 1.4 and higher\n\n### Known issues\n \n* PowerMock needs a workaround to run together with MockK [#79](https://github.com/mockk/mockk/issues/79#issuecomment-437646333). (not sure after workaround if it is generally usable or not, please somebody report it)\n* Inline functions cannot be mocked: see the discussion on [this issue](https://github.com/mockk/mockk/issues/27)\n* Spies, `mockkStatic` may not work on JDK 16+; `InaccessibleObjectException`/`IllegalAccessException`: [read more here](doc/md/jdk16-access-exceptions.md)\n* Using a spy with a suspending function [will give unexpected test results](https://github.com/mockk/mockk/issues/554)\n\nTable of contents:\n\n* auto-gen TOC:\n{:toc}\n\n## Examples, guides \u0026 articles\n\n### Kotlin Academy articles \u003cimg src=\"https://cdn-images-1.medium.com/letterbox/47/47/50/50/1*FUXqI88mttV_kV8aTrKjOg.png?source=logoAvatar-1f9f77b4b3d1---e57b304801ef\" width=\"20px\" /\u003e\n\nCheck the series of articles \"Mocking is not rocket science\" at [Kt. Academy](https://blog.kotlin-academy.com) describing MockK from the very basics of mocking up to description of all advanced features.\n\n - [Basics](https://blog.kotlin-academy.com/mocking-is-not-rocket-science-basics-ae55d0aadf2b)\n - [Expected behavior and behavior verification](https://blog.kotlin-academy.com/mocking-is-not-rocket-science-expected-behavior-and-behavior-verification-3862dd0e0f03)\n - [MockK features](https://blog.kotlin-academy.com/mocking-is-not-rocket-science-mockk-features-e5d55d735a98)\n - [MockK advanced features](https://blog.kotlin-academy.com/mocking-is-not-rocket-science-mockk-advanced-features-42277e5983b5)\n\n - [Testing Quarkus with Kotlin, JUnit and MockK](https://www.novatec-gmbh.de/en/blog/testing-quarkus-with-kotlin-junit-and-mockk/)\n - [Unraveling MockK's black magic(EN, translation)](https://chao2zhang.medium.com/unraveling-mockks-black-magic-e725c61ed9dd)\n - [Mockk Guidebook](https://notwoods.github.io/mockk-guidebook/)\n - [“Kotlin Unit Testing with Mockk” by Marco Cattaneo](https://link.medium.com/ObtQ4eBfg5) \n - [(Video) Use verify in MockK to validate function calls on mocked object](https://www.youtube.com/watch?v=J7_4WrImJPk)\n - [Testing With MockK paid course on raywenderlich.com](https://www.raywenderlich.com/5443751-testing-with-mockk)\n - TDD for Android video tutorial [part 1](https://www.youtube.com/watch?v=60KFJTb_HwU), [part 2](https://www.youtube.com/watch?v=32pnzGirvgM) by Ryan Kay    \n - [(Video)Android Developer Live Coding #13: Unit Testing with Mockk, Coroutines, Test Driven Development](https://www.youtube.com/watch?v=h8_LZn1DFDI)\n - [KotlinConf 2018 - Best Practices for Unit Testing in Kotlin by Philipp Hauer](https://www.youtube.com/watch?v=RX_g65J14H0\u0026feature=youtu.be\u0026t=940)\n - [kotlin-fullstack-sample uses MockK](https://github.com/Kotlin/kotlin-fullstack-sample/pull/28/files#diff-eade18fbfd0abfb6338dbfa647b3215dR17) project covered with tests\n - [DZone article](https://dzone.com/articles/new-mocking-tool-for-kotlin-an-alternative-to-java)\n - [Habrahabr article](https://habrahabr.ru/post/341202/) (RU)\n - [Mocking in Kotlin with MockK - Yannick De Turck](https://ordina-jworks.github.io/testing/2018/02/05/Writing-tests-in-Kotlin-with-MockK.html)\n \n### Japanese guides and articles\n - [Documentation translation to Japanese](https://qiita.com/yasuX/items/d3cfc9853c53dfaee222)\n - [Unraveling MockK's black magic / MockKの「黒魔術」を解明する (JP, but readable through chrome translator)](https://zenn.dev/oboenikui/articles/af44c158f9fa35)\n \n### Chinese guides and articles\n - [用 Kotlin + Mockito 寫單元測試會碰到什麼問題？](https://medium.com/joe-tsai/mockk-%E4%B8%80%E6%AC%BE%E5%BC%B7%E5%A4%A7%E7%9A%84-kotlin-mocking-library-part-1-4-39a85e42b8)\n - [MockK 功能介紹：mockk, every, Annotation, verify](https://medium.com/joe-tsai/mockk-%E4%B8%80%E6%AC%BE%E5%BC%B7%E5%A4%A7%E7%9A%84-kotlin-mocking-library-part-2-4-4be059331110)\n - [MockK 功能介紹：Relaxed Mocks, 再談 Verify, Capture](https://medium.com/joe-tsai/mockk-%E4%B8%80%E6%AC%BE%E5%BC%B7%E5%A4%A7%E7%9A%84-kotlin-mocking-library-part-3-4-79b40fb73964)\n - [如何測試 Static Method, Singleton](https://medium.com/joe-tsai/mockk-%E4%B8%80%E6%AC%BE%E5%BC%B7%E5%A4%A7%E7%9A%84-kotlin-mocking-library-part-4-4-f82443848a3a)\n\n### Korean guides and articles\n - [Documentation translation to Korean](https://www.devkuma.com/docs/kotlin/mockk/)\n - [MockK의 흑마술을 파헤치자!](https://sukyology.medium.com/mockk%EC%9D%98-%ED%9D%91%EB%A7%88%EC%88%A0%EC%9D%84-%ED%8C%8C%ED%97%A4%EC%B9%98%EC%9E%90-6fe907129c19)\n\n## Features\n\n### Annotations\n\nYou can use annotations to simplify the creation of mock objects:\n\n```kotlin\n\nclass TrafficSystem {\n  lateinit var car1: Car\n  \n  lateinit var car2: Car\n  \n  lateinit var car3: Car\n}\n\nclass CarTest {\n  @MockK\n  lateinit var car1: Car\n\n  @RelaxedMockK\n  lateinit var car2: Car\n\n  @MockK(relaxUnitFun = true)\n  lateinit var car3: Car\n\n  @SpyK\n  var car4 = Car()\n  \n  @InjectMockKs\n  var trafficSystem = TrafficSystem()\n  \n  @Before\n  fun setUp() = MockKAnnotations.init(this, relaxUnitFun = true) // turn relaxUnitFun on for all mocks\n\n  @Test\n  fun calculateAddsValues1() {\n      // ... use car1, car2, car3 and car4\n  }\n}\n```\n\nInjection first tries to match properties by name, then by class or superclass. \nCheck the `lookupType` parameter for customization. \n\nProperties are injected even if `private` is applied. Constructors for injection are selected from the biggest \nnumber of arguments to lowest.\n\n`@InjectMockKs` by default injects only `lateinit var`s or `var`s that are not assigned. \nTo change this, use `overrideValues = true`. This would assign the value even if it is already initialized somehow.\nTo inject `val`s, use `injectImmutable = true`. For a shorter notation use `@OverrideMockKs` which does the same as \n`@InjectMockKs` by default, but turns these two flags on.\n\n### JUnit4\n\nJUnit 4 exposes a rule-based API to allow for some automation following the test lifecycle. MockK includes a rule which uses this to set up and tear down your mocks without needing to manually call `MockKAnnotations.init(this)`. Example:\n\n```kotlin\nclass CarTest {\n  @get:Rule\n  val mockkRule = MockKRule(this)\n\n  @MockK\n  lateinit var car1: Car\n\n  @RelaxedMockK\n  lateinit var car2: Car\n\n  @Test\n  fun something() {\n     every { car1.drive() } just runs\n     every { car2.changeGear(any()) } returns true\n     // etc\n  }\n}\n```\n\n#### JUnit5\n\nIn JUnit5 you can use `MockKExtension` to initialize your mocks. \n\n```kotlin\n@ExtendWith(MockKExtension::class)\nclass CarTest {\n  @MockK\n  lateinit var car1: Car\n\n  @RelaxedMockK\n  lateinit var car2: Car\n\n  @MockK(relaxUnitFun = true)\n  lateinit var car3: Car\n\n  @SpyK\n  var car4 = Car()\n\n  @Test\n  fun calculateAddsValues1() {\n      // ... use car1, car2, car3 and car4\n  }\n}\n```\n\nAdditionally, it adds the possibility to use `@MockK` and `@RelaxedMockK` on test function parameters:\n\n```kotlin\n@Test\nfun calculateAddsValues1(@MockK car1: Car, @RelaxedMockK car2: Car) {\n  // ... use car1 and car2\n}\n```\n\nFinally, this extension will call `unmockkAll` and `clearAllMocks` in a `@AfterAll` callback, ensuring your test environment is clean after\neach test class execution.\nYou can disable this behavior by adding the `@MockKExtension.KeepMocks` annotation to your class or globally by setting \nthe `mockk.junit.extension.keepmocks=true` property.\n(Since v1.13.11)\nAlternatively, since `clearAllMocks` by default (`currentThreadOnly=false`) is not thread-safe, if you need to run test in parallel you can add the \n`MockKExtension.RequireParallelTesting` annotation to your class or set the `mockk.junit.extension.requireParallelTesting=true`\nproperty to disable calling it in the `@AfterAll` callback.\nIf `clearAllMocks` is explicitly called, you can supply `clearAllMocks(currentThreadOnly = true)` so that it only clears mocks created within the same thread (since v1.13.12).\n\n#### Automatic verification confirmation\n\nYou can make sure that all stubbed methods are actually verified by also annotating your test class with `@MockKExtension.ConfirmVerification`.\n\nThis will internally call `confirmVerified` on all mocks after each test, to make sure there are no unnecessary stubbings.\n\nPlease note that this behavior may not work as expected when running tests in your IDE, as it is Gradle who takes care of handling the exception being thrown when these `confirmVerified` calls fail.\n\n#### Automatic unnecessary stubbing check\n\nYou can make sure that all stubbed methods are useful - used at least once - by also annotating your test class with `@MockKExtension.CheckUnnecessaryStub`.\n\nThis will internally call `checkUnnecessaryStub` on all mocks after each test, to make sure there are no unnecessary stubbings.\n\n\n### Spy\n\nSpies allow you to mix mocks and real objects.\n\n```kotlin\nval car = spyk(Car()) // or spyk\u003cCar\u003e() to call the default constructor\n\ncar.drive(Direction.NORTH) // returns whatever the real function of Car returns\n\nverify { car.drive(Direction.NORTH) }\n\nconfirmVerified(car)\n```\n\nNote 1: the spy object is a copy of the passed object.\nNote 2: there is a known issue if using a spy with a suspending function: https://github.com/mockk/mockk/issues/554\n\n### Relaxed mock\n\nA `relaxed mock` is the mock that returns some simple value for all functions. \nThis allows you to skip specifying behavior for each case, while still stubbing things you need.\nFor reference types, chained mocks are returned.\n\n```kotlin\nval car = mockk\u003cCar\u003e(relaxed = true)\n\ncar.drive(Direction.NORTH) // returns null\n\nverify { car.drive(Direction.NORTH) }\n\nconfirmVerified(car)\n```\n\nNote: relaxed mocking is working badly with generic return types. A class cast exception is usually thrown in this case.\nOpt for stubbing manually in the case of a generic return type.\n\nWorkaround:\n\n```kotlin\nval func = mockk\u003c() -\u003e Car\u003e(relaxed = true) // in this case invoke function has generic return type\n\n// this line is workaround, without it the relaxed mock would throw a class cast exception on the next line\nevery { func() } returns Car() // or you can return mockk() for example \n\nfunc()\n```\n\n### Partial mocking\n\nSometimes, you need to stub some functions, but still call the real method on others, or on specific arguments.\nThis is possible by passing `callOriginal()` to `answers`, which works for both relaxed and non-relaxed mocks.\n\n```kotlin\nclass Adder {\n fun addOne(num: Int) = num + 1\n}\n\nval adder = mockk\u003cAdder\u003e()\n\nevery { adder.addOne(any()) } returns -1\nevery { adder.addOne(3) } answers { callOriginal() }\n\nassertEquals(-1, adder.addOne(2))\nassertEquals(4, adder.addOne(3)) // original function is called\n```\n\n### Mock relaxed for functions returning Unit\n\nIf you want `Unit`-returning functions to be relaxed, you can use `relaxUnitFun = true` as an argument to the `mockk` function, \n`@MockK`annotation or `MockKAnnotations.init` function.\n\nFunction:\n```kotlin\nmockk\u003cClassBeingMocked\u003e(relaxUnitFun = true)\n```\n\nAnnotation:\n```kotlin\n@MockK(relaxUnitFun = true)\nlateinit var mock1: ClassBeingMocked\ninit {\n    MockKAnnotations.init(this)\n}\n```\n\nMockKAnnotations.init:\n```kotlin\n@MockK\nlateinit var mock2: ClassBeingMocked\ninit {\n    MockKAnnotations.init(this, relaxUnitFun = true)\n}\n```\n\n### Object mocks\n\nObjects can be turned into mocks in the following way:\n\n```kotlin\nobject ObjBeingMocked {\n  fun add(a: Int, b: Int) = a + b\n}\n\nmockkObject(ObjBeingMocked) // applies mocking to an Object\n\nassertEquals(3, ObjBeingMocked.add(1, 2))\n\nevery { ObjBeingMocked.add(1, 2) } returns 55\n\nassertEquals(55, ObjBeingMocked.add(1, 2))\n```\n\nTo revert back, use `unmockkObject` or `unmockkAll` (more destructive: cancels object, static and constructor mocks)\n\n```kotlin\n@Before\nfun beforeTests() {\n    mockkObject(ObjBeingMocked)\n    every { ObjBeingMocked.add(1,2) } returns 55\n}\n\n@Test\nfun willUseMockBehaviour() {\n    assertEquals(55, ObjBeingMocked.add(1,2))\n}\n\n@After\nfun afterTests() {\n    unmockkObject(ObjBeingMocked)\n    // or unmockkAll()\n}\n```\n\nDespite the Kotlin language restrictions, you can create new instances of objects if required by testing logic:\n```kotlin\nval newObjectMock = mockk\u003cObjBeingMocked\u003e()\n```\n\n### Class mock\n\nSometimes you need a mock of an arbitrary class. Use `mockkClass` in those cases.\n\n```kotlin\nval car = mockkClass(Car::class)\n\nevery { car.drive(Direction.NORTH) } returns Outcome.OK\n\ncar.drive(Direction.NORTH) // returns OK\n\nverify { car.drive(Direction.NORTH) }\n```\n\n### Enumeration mocks\n\nEnums can be mocked using `mockkObject`:\n\n```kotlin\nenum class Enumeration(val goodInt: Int) {\n    CONSTANT(35),\n    OTHER_CONSTANT(45);\n}\n\nmockkObject(Enumeration.CONSTANT)\nevery { Enumeration.CONSTANT.goodInt } returns 42\nassertEquals(42, Enumeration.CONSTANT.goodInt)\n```\n\n### Constructor mocks\n\nSometimes, especially in code you don't own, you need to mock newly created objects.\nFor this purpose, the following constructs are provided:\n\n```kotlin\nclass MockCls {\n  fun add(a: Int, b: Int) = a + b\n}\n\nmockkConstructor(MockCls::class)\n\nevery { anyConstructed\u003cMockCls\u003e().add(1, 2) } returns 4\n\nassertEquals(4, MockCls().add(1, 2)) // note new object is created\n\nverify { anyConstructed\u003cMockCls\u003e().add(1, 2) }\n```\n\nThe basic idea is that just after the constructor of the mocked class is executed (any of them), objects become a `constructed mock`.  \nMocking behavior of such a mock is connected to the special `prototype mock` denoted by `anyConstructed\u003cMockCls\u003e()`.  \nThere is one instance per class of such a `prototype mock`. Call recording also happens to the `prototype mock`.  \nIf no behavior for the function is specified, then the original function is executed.  \n\nIn case a class has more than one constructor, each can be mocked separately:\n\n```kotlin\nclass MockCls(private val a: Int = 0) {\n  constructor(x: String) : this(x.toInt())  \n  fun add(b: Int) = a + b\n}\n\nmockkConstructor(MockCls::class)\n\nevery { constructedWith\u003cMockCls\u003e().add(1) } returns 2\nevery { \n    constructedWith\u003cMockCls\u003e(OfTypeMatcher\u003cString\u003e(String::class)).add(2) // Mocks the constructor which takes a String\n} returns 3\nevery {\n    constructedWith\u003cMockCls\u003e(EqMatcher(4)).add(any()) // Mocks the constructor which takes an Int\n} returns 4\n\nassertEquals(2, MockCls().add(1))\nassertEquals(3, MockCls(\"2\").add(2))\nassertEquals(4, MockCls(4).add(7))\n\nverify { \n    constructedWith\u003cMockCls\u003e().add(1)\n    constructedWith\u003cMockCls\u003e(EqMatcher(\"2\")).add(2)\n    constructedWith\u003cMockCls\u003e(EqMatcher(4)).add(7)\n}\n```\n\nNote that in this case, a `prototype mock` is created for every set of argument matchers passed to `constructedWith`.\n\n\n### Partial argument matching\n\nYou can mix both regular arguments and matchers:\n\n```kotlin\nval car = mockk\u003cCar\u003e()\n\nevery { \n  car.recordTelemetry(\n    speed = more(50),\n    direction = Direction.NORTH, // here eq() is used\n    lat = any(),\n    long = any()\n  )\n} returns Outcome.RECORDED\n\ncar.recordTelemetry(60, Direction.NORTH, 51.1377382, 17.0257142)\n\nverify { car.recordTelemetry(60, Direction.NORTH, 51.1377382, 17.0257142) }\n\nconfirmVerified(car)\n```\n\n### Chained calls\n\nYou can stub chains of calls:\n\n```kotlin\nval car = mockk\u003cCar\u003e()\n\nevery { car.door(DoorType.FRONT_LEFT).windowState() } returns WindowState.UP\n\ncar.door(DoorType.FRONT_LEFT) // returns chained mock for Door\ncar.door(DoorType.FRONT_LEFT).windowState() // returns WindowState.UP\n\nverify { car.door(DoorType.FRONT_LEFT).windowState() }\n\nconfirmVerified(car)\n```\n\nNote: if the function's return type is generic then the information about the actual type is gone.  \nTo make chained calls work, additional information is required.  \nMost of the time the framework will catch the cast exception and do `autohinting`.  \nIn the case it is explicitly required, use `hint` before making the next call.  \n\n```kotlin\nevery { obj.op2(1, 2).hint(Int::class).op1(3, 4) } returns 5\n```\n\n### Hierarchical mocking\n\nFrom version 1.9.1 mocks may be chained into hierarchies:\n\n```kotlin\ninterface AddressBook {\n    val contacts: List\u003cContact\u003e\n}\n\ninterface Contact {\n    val name: String\n    val telephone: String\n    val address: Address\n}\n\ninterface Address {\n    val city: String\n    val zip: String\n}\n\nval addressBook = mockk\u003cAddressBook\u003e {\n    every { contacts } returns listOf(\n        mockk {\n            every { name } returns \"John\"\n            every { telephone } returns \"123-456-789\"\n            every { address.city } returns \"New-York\"\n            every { address.zip } returns \"123-45\"\n        },\n        mockk {\n            every { name } returns \"Alex\"\n            every { telephone } returns \"789-456-123\"\n            every { address } returns mockk {\n                every { city } returns \"Wroclaw\"\n                every { zip } returns \"543-21\"\n            }\n        }\n    )\n}\n```\n\n### Capturing\n\nYou can capture an argument to a `CapturingSlot` or `MutableList`. \n\n`CapturingSlot` is usually created via factory method `slot\u003cT : Any?\u003e()` and is possible to capture nullable and non nullable types.\n`MutableList` is intended for capturing multiple values during testing.\n\n```kotlin\nenum class Direction { NORTH, SOUTH }\nenum class RecordingOutcome { RECORDED }\nenum class RoadType { HIGHWAY }\nclass Car {\n    fun recordTelemetry(speed: Double, direction: Direction, roadType: RoadType?): RecordingOutcome {\n        TODO(\"not implement for showcase\")\n    }\n}\n\nval car = mockk\u003cCar\u003e()\n// allow to capture parameter with non nullable type `Double`\nval speedSlot = slot\u003cDouble\u003e()\n// allow to capture parameter with nullable type `RoadType`\nval roadTypeSlot = slot\u003cRoadType?\u003e()\nval list = mutableListOf\u003cDouble\u003e()\n\nevery {\n    car.recordTelemetry(\n        speed = capture(speedSlot), // makes mock match calls with any value for `speed` and record it in a slot\n        direction = Direction.NORTH, // makes mock and capturing only match calls with specific `direction`. Use `any()` to match calls with any `direction`\n        roadType = captureNullable(roadTypeSlot), // makes mock match calls with any value for `roadType` and record it in a slot\n    )\n} answers {\n    println(\"Speed: ${speedSlot.captured}, roadType: ${roadTypeSlot.captured}\")\n\n    RecordingOutcome.RECORDED\n}\n\nevery {\n    car.recordTelemetry(\n        speed = capture(list),\n        direction = Direction.SOUTH,\n        roadType = captureNullable(roadTypeSlot),\n    )\n} answers {\n    println(\"Speed: ${list}, roadType: ${roadTypeSlot.captured}\")\n\n    RecordingOutcome.RECORDED\n}\n\ncar.recordTelemetry(speed = 15.0, direction = Direction.NORTH, null) // prints Speed: 15.0, roadType: null\ncar.recordTelemetry(speed = 16.0, direction = Direction.SOUTH, RoadType.HIGHWAY) // prints Speed: [16.0], roadType: HIGHWAY\n\nverifyOrder {\n    car.recordTelemetry(speed = or(15.0, 16.0), direction = any(), roadType = null)\n    car.recordTelemetry(speed = 16.0, direction = any(), roadType = RoadType.HIGHWAY)\n}\n\nconfirmVerified(car)\n```\n\n### Verification atLeast, atMost or exactly times\n\nYou can check the call count with the `atLeast`, `atMost` or `exactly` parameters:\n\n```kotlin\n\nval car = mockk\u003cCar\u003e(relaxed = true)\n\ncar.accelerate(fromSpeed = 10, toSpeed = 20)\ncar.accelerate(fromSpeed = 10, toSpeed = 30)\ncar.accelerate(fromSpeed = 20, toSpeed = 30)\n\n// all pass\nverify(atLeast = 3) { car.accelerate(allAny()) }\nverify(atMost  = 2) { car.accelerate(fromSpeed = 10, toSpeed = or(20, 30)) }\nverify(exactly = 1) { car.accelerate(fromSpeed = 10, toSpeed = 20) }\nverify(exactly = 0) { car.accelerate(fromSpeed = 30, toSpeed = 10) } // means no calls were performed\n\nconfirmVerified(car)\n```\n\nOr you can use `verifyCount`:\n\n```kotlin\n\nval car = mockk\u003cCar\u003e(relaxed = true)\n\ncar.accelerate(fromSpeed = 10, toSpeed = 20)\ncar.accelerate(fromSpeed = 10, toSpeed = 30)\ncar.accelerate(fromSpeed = 20, toSpeed = 30)\n\n// all pass\nverifyCount { \n    (3..5) * { car.accelerate(allAny(), allAny()) } // same as verify(atLeast = 3, atMost = 5) { car.accelerate(allAny(), allAny()) }\n    1 * { car.accelerate(fromSpeed = 10, toSpeed = 20) } // same as verify(exactly = 1) { car.accelerate(fromSpeed = 10, toSpeed = 20) }\n    0 * { car.accelerate(fromSpeed = 30, toSpeed = 10) } // same as verify(exactly = 0) { car.accelerate(fromSpeed = 30, toSpeed = 10) }\n}\n\nconfirmVerified(car)\n```\n\n### Verification order\n\n* `verifyAll` verifies that all calls happened without checking their order.\n* `verifySequence` verifies that the calls happened in a specified sequence.\n* `verifyOrder` verifies that calls happened in a specific order.\n* `wasNot Called` verifies that the mock (or the list of mocks) was not called at all.\n\n```kotlin\nclass MockedClass {\n    fun sum(a: Int, b: Int) = a + b\n}\n\nval obj = mockk\u003cMockedClass\u003e()\nval slot = slot\u003cInt\u003e()\n\nevery {\n    obj.sum(any(), capture(slot))\n} answers {\n    1 + firstArg\u003cInt\u003e() + slot.captured\n}\n\nobj.sum(1, 2) // returns 4\nobj.sum(1, 3) // returns 5\nobj.sum(2, 2) // returns 5\n\nverifyAll {\n    obj.sum(1, 3)\n    obj.sum(1, 2)\n    obj.sum(2, 2)\n}\n\nverifySequence {\n    obj.sum(1, 2)\n    obj.sum(1, 3)\n    obj.sum(2, 2)\n}\n\nverifyOrder {\n    obj.sum(1, 2)\n    obj.sum(2, 2)\n}\n\nval obj2 = mockk\u003cMockedClass\u003e()\nval obj3 = mockk\u003cMockedClass\u003e()\nverify {\n    listOf(obj2, obj3) wasNot Called\n}\n\nconfirmVerified(obj)\n```\n\n### Verification confirmation\n\nTo double-check that all calls were verified by `verify...` constructs, you can use `confirmVerified`:\n\n```kotlin\nconfirmVerified(mock1, mock2)\n```\n\nIt doesn't make much sense to use it for `verifySequence` and `verifyAll`, as these verification methods already exhaustively cover all calls with verification.\n\nIt will throw an exception if there are some calls left without verification.\n\nSome calls can be excluded from this confirmation, check the next section for more details.\n\n```kotlin\nval car = mockk\u003cCar\u003e()\n\nevery { car.drive(Direction.NORTH) } returns Outcome.OK\nevery { car.drive(Direction.SOUTH) } returns Outcome.OK\n\ncar.drive(Direction.NORTH) // returns OK\ncar.drive(Direction.SOUTH) // returns OK\n\nverify {\n    car.drive(Direction.SOUTH)\n    car.drive(Direction.NORTH)\n}\n\nconfirmVerified(car) // makes sure all calls were covered with verification\n```\n\n### Unnecessary stubbing\n\nBecause clean \u0026 maintainable test code requires zero unnecessary code, you can ensure that there is no unnecessary stubs.\n\n```kotlin\ncheckUnnecessaryStub(mock1, mock2)\n```\n\nIt will throw an exception if there are some declared calls on the mocks that are not used by the tested code.\nThis can happen if you have declared some really unnecessary stubs or if the tested code doesn't call an expected one.  \n\n\n### Recording exclusions\n\nTo exclude unimportant calls from being recorded, you can use `excludeRecords`:\n\n```kotlin\nexcludeRecords { mock.operation(any(), 5) }\n```\n\nAll matching calls will be excluded from recording. This may be useful if you are using exhaustive verification: `verifyAll`, `verifySequence` or `confirmVerified`.\n\n```kotlin\nval car = mockk\u003cCar\u003e()\n\nevery { car.drive(Direction.NORTH) } returns Outcome.OK\nevery { car.drive(Direction.SOUTH) } returns Outcome.OK\n\nexcludeRecords { car.drive(Direction.SOUTH) }\n\ncar.drive(Direction.NORTH) // returns OK\ncar.drive(Direction.SOUTH) // returns OK\n\nverify {\n    car.drive(Direction.NORTH)\n}\n\nconfirmVerified(car) // car.drive(Direction.SOUTH) was excluded, so confirmation is fine with only car.drive(Direction.NORTH)\n```\n\n### Verification timeout\n\nTo verify concurrent operations, you can use `timeout = xxx`:\n\n```kotlin\nmockk\u003cMockCls\u003e {\n    every { sum(1, 2) } returns 4\n\n    Thread {\n        Thread.sleep(2000)\n        sum(1, 2)\n    }.start()\n\n    verify(timeout = 3000) { sum(1, 2) }\n}\n```\n\nThis will wait until one of two following states: either verification is passed or the timeout is reached.\n\n### Returning Unit\n\nIf a function returns `Unit`, you can use the `justRun` construct:\n\n```kotlin\nclass MockedClass {\n    fun sum(a: Int, b: Int): Unit {\n        println(a + b)\n    }\n}\n\nval obj = mockk\u003cMockedClass\u003e()\n\njustRun { obj.sum(any(), 3) }\n\nobj.sum(1, 1)\nobj.sum(1, 2)\nobj.sum(1, 3)\n\nverify {\n    obj.sum(1, 1)\n    obj.sum(1, 2)\n    obj.sum(1, 3)\n}\n```\n\nOther ways to write `justRun { obj.sum(any(), 3) }`:\n - `every { obj.sum(any(), 3) } just Runs`\n - `every { obj.sum(any(), 3) } returns Unit`\n - `every { obj.sum(any(), 3) } answers { Unit }`\n\n### Coroutines\n\nTo mock coroutines you need to add another dependency to the support library.\n\u003ctable\u003e\n\u003ctr\u003e\n    \u003cth\u003eGradle\u003c/th\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n    \u003ctd\u003e\n\u003cpre\u003etestImplementation \"org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x\"\u003c/pre\u003e\n    \u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\u003ctable\u003e\n\u003ctr\u003e\n    \u003cth\u003eMaven\u003c/th\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd\u003e\n    \u003cpre\u003e\n\u0026lt;dependency\u0026gt;\n    \u0026lt;groupId\u0026gt;org.jetbrains.kotlinx\u0026lt;/groupId\u0026gt;\n    \u0026lt;artifactId\u0026gt;kotlinx-coroutines-core\u0026lt;/artifactId\u0026gt;\n    \u0026lt;version\u0026gt;x.x\u0026lt;/version\u0026gt;\n    \u0026lt;scope\u0026gt;test\u0026lt;/scope\u0026gt;\n\u0026lt;/dependency\u0026gt;\u003c/pre\u003e\n    \u003c/td\u003e\n\u003c/tr\u003e\n\u003c/table\u003e\n\nThen you can use `coEvery`, `coVerify`, `coMatch`, `coAssert`, `coRun`, `coAnswers` or `coInvoke` to mock suspend functions.\n\n```kotlin\nval car = mockk\u003cCar\u003e()\n\ncoEvery { car.drive(Direction.NORTH) } returns Outcome.OK\n\ncar.drive(Direction.NORTH) // returns OK\n\ncoVerify { car.drive(Direction.NORTH) }\n```\n\nAnd to simulate a never returning `suspend` function, you can use `coJustAwait`:\n\n```kotlin\nrunTest {\n    val car = mockk\u003cCar\u003e()\n\n    coJustAwait { car.drive(any()) } // car.drive(...) will never return\n\n    val job = launch(UnconfinedTestDispatcher()) {\n        car.drive(Direction.NORTH)\n    }\n\n    coVerify { car.drive(Direction.NORTH) }\n\n    job.cancelAndJoin() // Don't forget to cancel the job\n}\n```\n\nNote: there is a known issue if using a spy with a suspending function: https://github.com/mockk/mockk/issues/554\n\n### Top Level functions\n\nKotlin lets you declare functions that don’t belong to any class or object, called top-level functions. These calls are translated to static methods in `jvm` environments, and a special Java class is generated to hold the functions. These top-level functions can be mocked using `mockkStatic`. You just need to import the function and pass a reference as the argument:\n\n```kotlin\nimport com.cars.buildCar\n\nval testCar = Car()\nmockkStatic(::buildCar)\nevery { buildCar() } returns testCar\n\nassertEquals(testCar, buildCar())\n\nverify { buildCar() }\n```\n\nMocking a function will clear any existing mocks of other functions declared in the same file, equivalent to calling `clearStaticMockk` on the generated enclosing class.\n\n### Extension functions\n\nThere are three types of extension function in Kotlin:\n\n* class-wide\n* object-wide\n* module-wide\n\nFor an object or a class, you can mock extension functions just by creating a regular `mockk`:\n\n```kotlin\ndata class Obj(val value: Int)\n\nclass Ext {\n    fun Obj.extensionFunc() = value + 5\n}\n\nwith(mockk\u003cExt\u003e()) {\n    every {\n        Obj(5).extensionFunc()\n    } returns 11\n\n    assertEquals(11, Obj(5).extensionFunc())\n\n    verify {\n        Obj(5).extensionFunc()\n    }\n}\n```\n\nTo mock module-wide extension functions you need to\nbuild `mockkStatic(...)` with the module's class name as an argument.\nFor example \"pkg.FileKt\" for module `File.kt` in the `pkg` package.\n\n```kotlin\ndata class Obj(val value: Int)\n\n// declared in File.kt (\"pkg\" package)\nfun Obj.extensionFunc() = value + 5\n\nmockkStatic(\"pkg.FileKt\")\n\nevery {\n    Obj(5).extensionFunc()\n} returns 11\n\nassertEquals(11, Obj(5).extensionFunc())\n\nverify {\n    Obj(5).extensionFunc()\n}\n```\n\nIn `jvm` environments you can replace the class name with a function reference:\n```kotlin\nmockkStatic(Obj::extensionFunc)\n```\nNote that this will mock the whole `pkg.FileKt` class, and not just `extensionFunc`. \n\nThis syntax also applies for extension properties:\n```kotlin\nval Obj.squareValue get() = value * value\n\nmockkStatic(Obj::squareValue)\n```\n\nIf `@JvmName` is used, specify it as a class name.\n\nKHttp.kt:\n```kotlin\n@file:JvmName(\"KHttp\")\n\npackage khttp\n// ... KHttp code \n```\n\nTesting code:\n```kotlin\nmockkStatic(\"khttp.KHttp\")\n```\n\nSometimes you need to know a little bit more to mock an extension function. \nFor example the extension function `File.endsWith()` has a totally unpredictable `classname`:\n```kotlin\nmockkStatic(\"kotlin.io.FilesKt__UtilsKt\")\nevery { File(\"abc\").endsWith(any\u003cString\u003e()) } returns true\nprintln(File(\"abc\").endsWith(\"abc\"))\n```\nThis is standard Kotlin behaviour that may be unpredictable.\nUse `Tools -\u003e Kotlin -\u003e Show Kotlin Bytecode` or check `.class` files in JAR archive to detect such names.\n\n### Varargs\n\nFrom version 1.9.1, more extended vararg handling is possible:\n\n```kotlin\ninterface ClsWithManyMany {\n    fun manyMany(vararg x: Any): Int\n}\n\nval obj = mockk\u003cClsWithManyMany\u003e()\n\nevery { obj.manyMany(5, 6, *varargAll { it == 7 }) } returns 3\n\nprintln(obj.manyMany(5, 6, 7)) // 3\nprintln(obj.manyMany(5, 6, 7, 7)) // 3\nprintln(obj.manyMany(5, 6, 7, 7, 7)) // 3\n\nevery { obj.manyMany(5, 6, *anyVararg(), 7) } returns 4\n\nprintln(obj.manyMany(5, 6, 1, 7)) // 4\nprintln(obj.manyMany(5, 6, 2, 3, 7)) // 4\nprintln(obj.manyMany(5, 6, 4, 5, 6, 7)) // 4\n\nevery { obj.manyMany(5, 6, *varargAny { nArgs \u003e 5 }, 7) } returns 5\n\nprintln(obj.manyMany(5, 6, 4, 5, 6, 7)) // 5\nprintln(obj.manyMany(5, 6, 4, 5, 6, 7, 7)) // 5\n\nevery {\n    obj.manyMany(5, 6, *varargAny {\n        if (position \u003c 3) it == 3 else it == 4\n    }, 7)\n} returns 6\n\nprintln(obj.manyMany(5, 6, 3, 4, 7)) // 6\nprintln(obj.manyMany(5, 6, 3, 4, 4, 7)) // 6\n```\n\n### Private functions mocking / dynamic calls\n\nIF you need to mock private functions, you can do it via a dynamic call.\n```kotlin\nclass Car {\n    fun drive() = accelerate()\n\n    private fun accelerate() = \"going faster\"\n}\n\nval mock = spyk\u003cCar\u003e(recordPrivateCalls = true)\n\nevery { mock[\"accelerate\"]() } returns \"going not so fast\"\n\nassertEquals(\"going not so fast\", mock.drive())\n\nverifySequence {\n    mock.drive()\n    mock[\"accelerate\"]()\n}\n```\n\nIf you want to verify private calls, you should create a `spyk` with `recordPrivateCalls = true`\n\nAdditionally, a more verbose syntax allows you to get and set properties, combined with the same dynamic calls:\n\n```kotlin\nval mock = spyk(Team(), recordPrivateCalls = true)\n\nevery { mock getProperty \"speed\" } returns 33\nevery { mock setProperty \"acceleration\" value less(5) } just runs\njustRun { mock invokeNoArgs \"privateMethod\" }\nevery { mock invoke \"openDoor\" withArguments listOf(\"left\", \"rear\") } returns \"OK\"\n\nverify { mock getProperty \"speed\" }\nverify { mock setProperty \"acceleration\" value less(5) }\nverify { mock invoke \"openDoor\" withArguments listOf(\"left\", \"rear\") }\n```\n\n### Property backing fields\n\nYou can access the backing fields via `fieldValue` and use `value` for the value being set.\n\nNote: in the examples below, we use `propertyType` to specify the type of the `fieldValue`.\nThis is needed because it is possible to capture the type automatically for the getter.\nUse `nullablePropertyType` to specify a nullable type.\n\n**Note:** This is only for public fields. It is nearly impossible to mock private properties as they don't have getter methods attached. Use Java reflection to make the field accessible or use `@VisibleForTesting` annotation in the source.\n\n```kotlin\nval mock = spyk(MockCls(), recordPrivateCalls = true)\n\nevery { mock.property } answers { fieldValue + 6 }\nevery { mock.property = any() } propertyType Int::class answers { fieldValue += value }\nevery { mock getProperty \"property\" } propertyType Int::class answers { fieldValue + 6 }\nevery { mock setProperty \"property\" value any\u003cInt\u003e() } propertyType Int::class answers  { fieldValue += value }\nevery {\n    mock.property = any()\n} propertyType Int::class answers {\n    fieldValue = value + 1\n} andThen {\n    fieldValue = value - 1\n}\n```\n\n### Multiple interfaces\n\nAdding additional behaviours via interfaces and stubbing them:\n\n```kotlin\nval spy = spyk(System.out, moreInterfaces = arrayOf(Runnable::class))\n\nspy.println(555)\n\nevery {\n    (spy as Runnable).run()\n} answers {\n    (self as PrintStream).println(\"Run! Run! Run!\")\n}\n\nval thread = Thread(spy as Runnable)\nthread.start()\nthread.join()\n```\n\n### Mocking Nothing\n\nNothing special here. If you have a function returning `Nothing`:\n\n```kotlin\nfun quit(status: Int): Nothing {\n    exitProcess(status)\n}\n```\n\nThen you can for example throw an exception as behaviour:\n\n```kotlin\nevery { quit(1) } throws Exception(\"this is a test\")\n```\n\n### Clearing vs Unmocking\n\n* clear - deletes the internal state of objects associated with a mock, resulting in an empty object\n* unmock - re-assigns transformation of classes back to original state prior to mock\n\n### Scoped mocks\n\nA Scoped mock is a mock that automatically unmocks itself after the code block passed as a parameter has been executed.\nYou can use the `mockkObject`, `mockkStatic` and `mockkConstructor` functions.\n\n```kotlin\nobject ObjBeingMocked {\n fun add(a: Int, b: Int) = a + b\n}\n\n// ObjBeingMocked will be unmocked after this scope\nmockkObject(ObjBeingMocked) {\n assertEquals(3, ObjBeingMocked.add(1, 2))\n every { ObjBeingMocked.add(1, 2) } returns 55\n assertEquals(55, ObjBeingMocked.add(1, 2))\n}\n```\n\n## Matcher extensibility\n\nA very simple way to create new matchers is by attaching a function \nto `MockKMatcherScope` or `MockKVerificationScope` and using the `match` function:\n\n```kotlin\nfun MockKMatcherScope.seqEq(seq: Sequence\u003cString\u003e) = match\u003cSequence\u003cString\u003e\u003e {\n    it.toList() == seq.toList()\n}\n```\n\nIt's also possible to create more advanced matchers by implementing the `Matcher` interface. \n\n### Custom matchers\n\nExample of a custom matcher that compares list without order:\n\n```kotlin \n@Test\nfun test() {\n    class MockCls {\n        fun op(a: List\u003cInt\u003e) = a.reversed()\n    }\n\n    val mock = mockk\u003cMockCls\u003e()\n\n    every { mock.op(any()) } returns listOf(5, 6, 9)\n\n    println(mock.op(listOf(1, 2, 3)))\n\n    verify { mock.op(matchListWithoutOrder(3, 2, 1)) }\n\n}\n\ndata class ListWithoutOrderMatcher\u003cT\u003e(\n    val expectedList: List\u003cT\u003e,\n    val refEq: Boolean\n) : Matcher\u003cList\u003cT\u003e\u003e {\n    val map = buildCountsMap(expectedList, refEq)\n\n    override fun match(arg: List\u003cT\u003e?): Boolean {\n        if (arg == null) return false\n        return buildCountsMap(arg, refEq) == map\n    }\n\n    private fun buildCountsMap(list: List\u003cT\u003e, ref: Boolean): Map\u003cAny?, Int\u003e {\n        val map = mutableMapOf\u003cAny?, Int\u003e()\n\n        for (item in list) {\n            val key = when {\n                item == null -\u003e nullKey\n                refEq -\u003e InternalPlatform.ref(item)\n                else -\u003e item\n            }\n            map.compute(key, { _, value -\u003e (value ?: 0) + 1 })\n        }\n\n        return map\n    }\n\n    override fun toString() = \"matchListWithoutOrder($expectedList)\"\n\n    @Suppress(\"UNCHECKED_CAST\")\n    override fun substitute(map: Map\u003cAny, Any\u003e): Matcher\u003cList\u003cT\u003e\u003e {\n        return copy(expectedList = expectedList.map { map.getOrDefault(it as Any?, it) } as List\u003cT\u003e)\n    }\n\n    companion object {\n        val nullKey = Any()\n    }\n}\n\ninline fun \u003creified T : List\u003cE\u003e, E : Any\u003e MockKMatcherScope.matchListWithoutOrder(\n    vararg items: E,\n    refEq: Boolean = true\n): T = match(ListWithoutOrderMatcher(listOf(*items), refEq))\n```\n\n### Reflection matchers\n\nExample using reflection to mock all methods on a builder-style object\n\n```kotlin\nval builderFunctions = MyBuilder::class.memberFunctions.filter { it.returnType.classifier == MyBuilder::class }\nval builderMock = mockk\u003cMyBuilder\u003e {\n  builderFunctions.forEach { func -\u003e\n    every {\n      val params = listOf\u003cAny?\u003e(builderMock) + func.parameters.drop(1).map { any(it.type.classifier as KClass\u003cAny\u003e) }\n      func.call(*params.toTypedArray())\n    } answers { \n      this@mockk\n    }\n  }\n}\n```\n\n## Settings file\n\nTo adjust parameters globally, there are a few settings you can specify in a resource file.\n\nHow to use: \n 1. Create a `io/mockk/settings.properties` file in `src/test/resources`.\n 2. Put any of the following options:\n```properties\nrelaxed=true|false\nrelaxUnitFun=true|false\nrecordPrivateCalls=true|false\nstackTracesOnVerify=true|false\nstackTracesAlignment=left|center\nfailOnSetBackingFieldException=true|false\n```\n\n* `stackTracesAlignment` determines whether to align the stack traces to the center (default),\n or to the left (more consistent with usual JVM stackTraces).\n* If `failOnSetBackingFieldException` (`false` by default) is set to `true`, tests fail if a\n backing field could not be set. Otherwise, only the warning \"Failed to set backing field\" will be logged.\n See [here](https://github.com/mockk/mockk/issues/1291) for more details.\n\n## DSL tables\n\nHere are a few tables to help you master the DSL.\n\n### Top level functions\n\n| Function                  | Description                                                                                                |\n|---------------------------|------------------------------------------------------------------------------------------------------------|\n| `mockk\u003cT\u003e(...)`           | builds a regular mock                                                                                      |\n| `spyk\u003cT\u003e()`               | builds a spy using the default constructor                                                                 |\n| `spyk(obj)`               | builds a spy by copying from `obj`                                                                         |\n| `slot`                    | creates a capturing slot                                                                                   |\n| `every`                   | starts a stubbing block                                                                                    |\n| `coEvery`                 | starts a stubbing block for coroutines                                                                     |\n| `verify`                  | starts a verification block                                                                                |\n| `coVerify`                | starts a verification block for coroutines                                                                 |\n| `verifyAll`               | starts a verification block that should include all calls                                                  |\n| `coVerifyAll`             | starts a verification block that should include all calls for coroutines                                   |\n| `verifyOrder`             | starts a verification block that checks the order                                                          |\n| `coVerifyOrder`           | starts a verification block that checks the order for coroutines                                           |\n| `verifySequence`          | starts a verification block that checks whether all calls were made in a specified sequence                |\n| `coVerifySequence`        | starts a verification block that checks whether all calls were made in a specified sequence for coroutines |\n| `excludeRecords`          | exclude some calls from being recorded                                                                     |\n| `confirmVerified`         | confirms that all recorded calls were verified                                                             |\n| `checkUnnecessaryStub`    | confirms that all recorded calls are used at least once                                                    |\n| `clearMocks`              | clears specified mocks                                                                                     |\n| `registerInstanceFactory` | allows you to redefine the way of instantiation for certain object                                         |\n| `mockkClass`              | builds a regular mock by passing the class as parameter                                                    |\n| `mockkObject`             | turns an object into an object mock, or clears it if was already transformed                               |\n| `unmockkObject`           | turns an object mock back into a regular object                                                            |\n| `mockkStatic`             | makes a static mock out of a class, or clears it if it was already transformed                             |\n| `unmockkStatic`           | turns a static mock back into a regular class                                                              |\n| `clearStaticMockk`        | clears a static mock                                                                                       |\n| `mockkConstructor`        | makes a constructor mock out of a class, or clears it if it was already transformed                        |\n| `unmockkConstructor`      | turns a constructor mock back into a regular class                                                         |\n| `clearConstructorMockk`   | clears the constructor mock                                                                                |\n| `unmockkAll`              | unmocks object, static and constructor mocks                                                               |\n| `clearAllMocks`           | clears regular, object, static and constructor mocks                                                       |\n\n\n### Matchers\n\nBy default, simple arguments are matched using `eq()`\n\n| Matcher                                                 | Description                                                                                            |\n|---------------------------------------------------------|--------------------------------------------------------------------------------------------------------|\n| `any()`                                                 | matches any argument                                                                                   |\n| `any(Class)`                                            | matches any argument of the give Class (for reflective mocking)                                        |\n| `allAny()`                                              | special matcher that uses `any()` instead of `eq()` for matchers that are provided as simple arguments |\n| `isNull()`                                              | checks if the value is null                                                                            |\n| `isNull(inverse=true)`                                  | checks if the value is not null                                                                        |\n| `ofType(type)`                                          | checks if the value belongs to the type                                                                |\n| `match { it.startsWith(\"string\") }`                     | matches via the passed predicate                                                                       |\n| `coMatch { it.startsWith(\"string\") }`                   | matches via the passed coroutine predicate                                                             |\n| `matchNullable { it?.startsWith(\"string\") }`            | matches nullable value via the passed predicate                                                        |\n| `coMatchNullable { it?.startsWith(\"string\") }`          | matches nullable value via the passed coroutine predicate                                              |\n| `eq(value)`                                             | matches if the value is equal to the provided value via the `deepEquals` function                      |\n| `eq(value, inverse=true)`                               | matches if the value is not equal to the provided value via the `deepEquals` function                  |\n| `neq(value)`                                            | matches if the value is not equal to the provided value via the `deepEquals` function                  |\n| `refEq(value)`                                          | matches if the value is equal to the provided value via reference comparison                           |\n| `refEq(value, inverse=true)`                            | matches if the value is not equal to the provided value via reference comparison                       ||\n| `nrefEq(value)`                                         | matches if the value is not equal to the provided value via reference comparison                       ||\n| `cmpEq(value)`                                          | matches if the value is equal to the provided value via the `compareTo` function                       |\n| `less(value)`                                           | matches if the value is less than the provided value via the `compareTo` function                      |\n| `more(value)`                                           | matches if the value is more than the provided value via the `compareTo` function                      |\n| `less(value, andEquals=true)`                           | matches if the value is less than or equal to the provided value via the `compareTo` function          |\n| `more(value, andEquals=true)`                           | matches if the value is more than or equal to the provided value via the `compareTo` function          |\n| `range(from, to, fromInclusive=true, toInclusive=true)` | matches if the value is in range via the `compareTo` function                                          |\n| `and(left, right)`                                      | combines two matchers via a logical and                                                                |\n| `or(left, right)`                                       | combines two matchers via a logical or                                                                 |\n| `not(matcher)`                                          | negates the matcher                                                                                    |\n| `capture(slot)`                                         | captures a Non Nullable value to a `CapturingSlot`                                                     |\n| `captureNullable(slot)`                                 | captures a Nullable value to a `CapturingSlot`                                                         |\n| `capture(mutableList)`                                  | captures a value to a list                                                                             |\n| `captureNullable(mutableList)`                          | captures a value to a list together with null values                                                   |\n| `captureLambda()`                                       | captures a lambda                                                                                      |\n| `captureCoroutine()`                                    | captures a coroutine                                                                                   |\n| `invoke(...)`                                           | calls a matched argument                                                                               |\n| `coInvoke(...)`                                         | calls a matched argument for a coroutine                                                               |\n| `hint(cls)`                                             | hints the next return type in case it's gotten erased                                                  |\n| `anyVararg()`                                           | matches any elements in a vararg                                                                       |\n| `varargAny(matcher)`                                    | matches if any element matches the matcher                                                             |\n| `varargAll(matcher)`                                    | matches if all elements match the matcher                                                              |\n| `any...Vararg()`                                        | matches any elements in vararg (specific to primitive type)                                            |\n| `varargAny...(matcher)`                                 | matches if any element matches the matcher (specific to the primitive type)                            |\n| `varargAll...(matcher)`                                 | matches if all elements match the matcher (specific to the primitive type)                             |\n\nA few special matchers available in verification mode only:\n\n| Matcher                      | Description                                                          |\n|------------------------------|----------------------------------------------------------------------|\n| `withArg { code }`           | matches any value and allows to execute some code                    |\n| `withNullableArg { code }`   | matches any nullable value and allows to execute some code           |\n| `coWithArg { code }`         | matches any value and allows to execute some coroutine code          |\n| `coWithNullableArg { code }` | matches any nullable value and allows to execute some coroutine code |\n\n### Validators\n\n| Validator                                       | Description                                                                                     |\n|-------------------------------------------------|-------------------------------------------------------------------------------------------------|\n| `verify { mock.call() }`                        | Do unordered verification that a call was performed                                             |\n| `verify(inverse=true) { mock.call() }`          | Do unordered verification that a call was not performed                                         |\n| `verify(atLeast=n) { mock.call() }`             | Do unordered verification that a call was performed at least `n` times                          |\n| `verify(atMost=n) { mock.call() }`              | Do unordered verification that a call was performed at most `n` times                           |\n| `verify(exactly=n) { mock.call() }`             | Do unordered verification that a call was performed exactly `n` times                           |\n| `verifyAll { mock.call1(); mock.call2() }`      | Do unordered verification that only the specified calls were executed for the mentioned mocks   |\n| `verifyOrder { mock.call1(); mock.call2() }`    | Do verification that the sequence of calls went one after another                               |\n| `verifySequence { mock.call1(); mock.call2() }` | Do verification that only the specified sequence of calls were executed for the mentioned mocks |\n| `verify { mock wasNot Called }`                 | Do verification that a mock was not called                                                      |\n| `verify { listOf(mock1, mock2) wasNot Called }` | Do verification that a list of mocks were not called                                            |\n\n### Answers\n\nAn Answer can be followed up by one or more additional answers.\n\n| Answer                       | Description                                                                                                        |\n|------------------------------|--------------------------------------------------------------------------------------------------------------------|\n| `returns value`              | specify that the matched call returns a specified value                                                            |\n| `returnsMany list`           | specify that the matched call returns a value from the list, with subsequent calls returning the next element      |\n| `returnsArgument(n)`         | specify that the matched call returns the nth argument of that call                                                |\n| `throws ex`                  | specify that the matched call throws an exception                                                                  |\n| `throwsMany list`            | specify that the matched call throws an exception from the list, with subsequent calls throwing the next exception |\n| `answers { code }`           | specify that the matched call answers with a code block scoped with `answer scope`                                 |\n| `coAnswers { code }`         | specify that the matched call answers with a coroutine code block  with `answer scope`                             |\n| `answers answerObj`          | specify that the matched call answers with an Answer object                                                        |\n| `answers { nothing }`        | specify that the matched call answers null                                                                         |\n| `just Runs`                  | specify that the matched call is returning Unit (returns null)                                                     |\n| `just Awaits`                | specify that the matched call never returns (available since v1.13.3)                                              |\n| `propertyType Class`         | specify the type of the backing field accessor                                                                     |\n| `nullablePropertyType Class` | specify the type of the backing field accessor as a nullable type                                                  |\n\n\n### Additional answer(s)\n\nA next answer is returned on each consequent call and the last value is persisted.\nSo this is similar to the `returnsMany` semantics.\n\n| Additional answer         | Description                                                                                                        |\n|---------------------------|--------------------------------------------------------------------------------------------------------------------|\n| `andThen value`           | specify that the matched call returns one specified value                                                          |\n| `andThenMany list`        | specify that the matched call returns a value from the list, with subsequent calls returning the next element      |\n| `andThenThrows ex`        | specify that the matched call throws an exception                                                                  |\n| `andThenThrowsMany ex`    | specify that the matched call throws an exception from the list, with subsequent calls throwing the next exception |\n| `andThen { code }`        | specify that the matched call answers with a code block scoped with `answer scope`                                 |\n| `coAndThen { code }`      | specify that the matched call answers with a coroutine code block with `answer scope`                              |\n| `andThenAnswer answerObj` | specify that the matched call answers with an Answer object                                                        |\n| `andThen { nothing }`     | specify that the matched call answers null                                                                         |\n| `andThenJust Runs`        | specify that the matched call is returning Unit (available since v1.12.2)                                          |\n| `andThenJust Awaits`      | specify that the matched call is never returning (available since v1.13.3)                                         |\n\n### Answer scope\n\n| Parameter                     | Description                                                             |\n|-------------------------------|-------------------------------------------------------------------------|\n| `call`                        | a call object that consists of an invocation and a matcher              |\n| `invocation`                  | contains information regarding the actual function invoked              |\n| `matcher`                     | contains information regarding the matcher used to match the invocation |\n| `self`                        | reference to the object invocation made                                 |\n| `method`                      | reference to the function invocation made                               |\n| `args`                        | reference to the invocation arguments                                   |\n| `nArgs`                       | number of invocation arguments                                          |\n| `arg(n)`                      | nth argument                                                            |\n| `firstArg()`                  | first argument                                                          |\n| `secondArg()`                 | second argument                                                         |\n| `thirdArg()`                  | third argument                                                          |\n| `lastArg()`                   | last argument                                                           |\n| `captured()`                  | the last element in the list for convenience when capturing to a list   |\n| `lambda\u003c...\u003e().invoke()`      | call the captured lambda                                                |\n| `coroutine\u003c...\u003e().coInvoke()` | call the captured coroutine                                             |\n| `nothing`                     | null value for returning `nothing` as an answer                         |\n| `fieldValue`                  | accessor to the property backing field                                  |\n| `fieldValueAny`               | accessor to the property backing field with `Any?` type                 |\n| `value`                       | value being set, cast to the same type as the property backing field    |\n| `valueAny`                    | value being set, with `Any?` type                                       |\n| `callOriginal`                | calls the original function                                             |\n\n### Vararg scope\n\n| Parameter  | Description                                   |\n|------------|-----------------------------------------------|\n| `position` | the position of an argument in a vararg array |\n| `nArgs`    | overall count of arguments in a vararg array  |\n\n## Restricted Mocking in MockK\n\n### Overview\n\n**Restricted Mocking** is a feature in MockK designed to **prevent the mocking of classes** that are problematic to mock.  \nThese classes often indicate poor test design and can lead to **unreliable** or **misleading test results**.\n\nThe primary goal is to:\n- **Encourage better testing practices**\n- **Promote code maintainability**\n- **Avoid mocking classes tied to system operations or critical data structures**\n\n\n### Why Restrict Mocking?\n\nMocking certain classes can cause several issues:\n\n| 🚩 **Problem**              | ⚠️ **Impact**                                                               |\n|-----------------------------|-----------------------------------------------------------------------------|\n| **False sense of security** | Tests may pass even when the implementation is fragile or incorrect.        |\n| **Tight coupling**          | Tests become overly dependent on low-level implementation details.          |\n| **Hard-to-maintain tests**  | Changes in code can break unrelated tests, increasing maintenance overhead. |\n| **Code smells**             | Mocking system-level or value-type classes often signals poor architecture. |\n\n\n### Default Restricted Classes\n\nThe following classes are **restricted from being mocked by default**:\n\n| **Class**              | **Description**                                                       | **Includes Subtypes?** |\n|------------------------|-----------------------------------------------------------------------|------------------------|\n| `java.lang.System`     | System-related APIs (`System.currentTimeMillis()`, `System.getenv()`) | ✅ Yes                  |\n| `java.util.Collection` | Collections like `List`, `Set`, and `Queue`                           | ✅ Yes                  |\n| `java.util.Map`        | Key-value data structures like `HashMap`                              | ✅ Yes                  |\n| `java.io.File`         | File I/O classes (should be abstracted instead)                       | ✅ Yes                  |\n| `java.nio.file.Path`   | Path manipulation classes for file systems                            | ✅ Yes                  |\n\n⚠️ **Note:**  \n**All subclasses and implementations** of these classes are also restricted.  \nFor example:\n- `ArrayList` and `HashSet` (subtypes of `Collection`)\n- `HashMap` (subtype of `Map`)\n- Custom classes that extend `File` or implement `Path`\n\n### How to Configure Restricted Mocking\n\nYou can configure Restricted Mocking behavior using the `mockk.properties` file.\n\n#### 1. Creating the `mockk.properties` File\n\nPlace the file in one of the following directories:\n\n```plaintext\nsrc/test/resources/mockk.properties\n```\n\n#### 2. Configuration Options\n\n```\n# List of restricted classes (fully qualified names, separated by commas)\nrestrictedClasses=com.foo.Bar,com.foo.Baz\n\n# Whether to throw an exception when mocking restricted classes\nmockk.throwExceptionOnBadMock=true\n```\n\n| **Property**                    | **Description**                                                                                 | **Default Value** |\n|---------------------------------|-------------------------------------------------------------------------------------------------|-------------------|\n| `mockk.restrictedClasses`       | Add fully qualified names of classes to restrict. Supports both system and custom classes.      | N/A               |\n| `mockk.throwExceptionOnBadMock` | `true`: Throws an exception when mocking restricted classes. \u003cbr\u003e `false`: Logs a warning only. | `false`           |\n\n⚠️ **Note:**\n\nIf mockk.throwExceptionOnBadMock is not set, it will default to false, meaning only warnings will be logged.\n\nTo strictly prevent mocking restricted classes, explicitly set:\n```\nmockk.throwExceptionOnBadMock=true\n```\n\n### Behavior When Mocking Restricted Classes\n\n#### When `mockk.throwExceptionOnBadMock=false` (Default)\n\n```kotlin\n@Test\nfun `when throwExceptionOnBadMock is false should not throw exception for collections`() {\n    val mockList = mockk\u003cList\u003cString\u003e\u003e()\n    every { mockList.size } returns 0\n\n    mockList.size shouldBe 0\n}\n```\n\n- Result:\n  - A warning log is generated, but the test passes.\n\n- Log Example:\n  - List should not be mocked! Consider refactoring your test.\n\n#### When `mockk.throwExceptionOnBadMock=true`\n```kotlin\n@Test\nfun `when throwExceptionOnBadMock is true should throw MockKException for collections`() {\n    assertThrows\u003cMockKException\u003e {\n        mockk\u003cList\u003cString\u003e\u003e()  // Throws MockKException\n    }\n}\n```\n\n- Result:\n  - A MockKException is thrown, causing the test to fail.\n- Exception Example:\n  - MockKException: Mocking java.util.HashMap is not allowed!\n\n### Custom Class Restriction Example\n\nYou can restrict **custom classes** from being mocked using the `mockk.properties` configuration file.  \nThis helps enforce proper testing practices even within your own codebase.\n\n#### Example 1: Mocking a Restricted Custom Class (Throws Exception)\n\nAdd the following to your `mockk.properties` file:\n\n```kotlin\npackage com.foo\n\nclass Foo {\n    fun doSomething(): String = \"print Foo\"\n}\n```\n\n```kotlin\npackage com.bar\n\nclass Bar {\n    fun doSomething(): String = \"print Bar\"\n}\n\nclass Baz : Bar() { \n    fun doSomething(): String = \"print Baz\"\n}\n```\n\n```properties\n# Restrict custom classes from being mocked\nmockk.restrictedClasses=com.foo.Bar,com.foo.Baz\n\n# Throw an exception when attempting to mock restricted classes\nmockk.throwExceptionOnBadMock=true\n```\n\n```kotlin\nimport io.mockk.mockk\nimport io.mockk.MockKException\nimport kotlin.test.Test\nimport kotlin.test.assertFailsWith\n\nclass RestrictedTest {\n    @Test\n    fun `should throw exception when mocking restricted class Foo`() {\n        assertFailsWith\u003cMockKException\u003e {\n            mockk\u003cFoo\u003e()  // 🚫 This will throw an exception\n        }\n    }\n    \n    @Test\n    fun `should throw exception when mocking restricted class Bar`() {\n        assertFailsWith\u003cMockKException\u003e {\n            mockk\u003cBar\u003e()  // 🚫 This will throw an exception\n        }\n    }\n\n    @Test\n    fun `should throw exception when mocking restricted class Baz`() {\n        assertFailsWith\u003cMockKException\u003e {\n            mockk\u003cBaz\u003e()  // 🚫 This will throw an exception\n        }\n    }\n}\n```\n\n## Funding\n\nYou can also support this project by becoming a sponsor. Your logo will show up here with a link to your website.\n\n### Sponsors\n\n\u003ca href=\"https://opencollective.com/mockk/sponsor/0/website\" target=\"_blank\"\u003e\n  \u003cimg src=\"https://opencollective.com/mockk/sponsor/0/avatar.svg\"/\u003e\n\u003c/a\u003e\n\u003ca href=\"https://opencollective.com/mockk/sponsor/1/website\" target=\"_blank\"\u003e\n  \u003cimg src=\"https://opencollective.com/mockk/sponsor/1/avatar.svg\"/\u003e\n\u003c/a\u003e\n\n### Backers\n\nThank you to all our backers! 🙏\n\n\u003ca href=\"https://opencollective.com/mockk#backers\" target=\"_blank\"\u003e\n  \u003cimg src=\"https://opencollective.com/mockk/backers.svg?width=890\"/\u003e\n\u003c/a\u003e\n\n### Contributors\n\nThis project exists thanks to all the people who contribute.\n\n\u003ca href=\"https://github.com/mockk/mockk/graphs/contributors\"\u003e\n  \u003cimg src=\"https://opencollective.com/mockk/contributors.svg?width=890\" /\u003e\n\u003c/a\u003e\n\n## Getting Help\n\nTo ask questions, please use Stack Overflow or Gitter.\n\n* Chat/Gitter: [https://gitter.im/mockk-io/Lobby](https://gitter.im/mockk-io/Lobby)\n* Stack Overflow: [http://stackoverflow.com/questions/tagged/mockk](https://stackoverflow.com/questions/tagged/mockk)\n\nTo report bugs, please use the GitHub project.\n\n* Project Page: [https://github.com/mockk/mockk](https://github.com/mockk/mockk)\n* Reporting Bugs: [https://github.com/mockk/mockk/issues](https://github.com/mockk/mockk/issues)\n","funding_links":["https://opencollective.com/mockk"],"categories":["Libraries","Mock","测试","Kotlin","Mocking","Testing"],"sub_categories":["Test","Helper","SQL"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmockk%2Fmockk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmockk%2Fmockk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmockk%2Fmockk/lists"}