[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-7246":3},{"id":4,"name":5,"fullName":6,"owner":5,"repo":5,"description":7,"homepage":8,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":15,"stars7d":16,"stars30d":17,"stars90d":15,"forks30d":15,"starsTrendScore":18,"compositeScore":19,"rankGlobal":9,"rankLanguage":9,"license":20,"archived":21,"fork":21,"defaultBranch":22,"hasWiki":23,"hasPages":23,"topics":24,"createdAt":9,"pushedAt":9,"updatedAt":35,"readmeContent":36,"aiSummary":37,"trendingCount":15,"starSnapshotCount":15,"syncStatus":18,"lastSyncTime":38,"discoverSource":39},7246,"mockk","mockk\u002Fmockk","mocking library for Kotlin","https:\u002F\u002Fmockk.io",null,"Kotlin",5744,409,54,290,0,4,7,2,66.54,"Apache License 2.0",false,"master",true,[25,26,27,28,29,30,31,32,33,34],"argument-matchers","chain-calls","hacktoberfest","kotlin","matcher","mock","mocking-framework","tdd","testing","verification","2026-06-12 04:00:32","\u003Cdiv align=\"center\">\n    \u003Cimg src=\"doc\u002Flogo-site.png\" width=\"400\" align=\"center\" alt=\"drawing\"\u002F>\n    \u003Cimg src=\"doc\u002Fkotlin-logo.svg\" width=\"400\" align=\"center\" alt=\"drawing\"\u002F>\n\u003C\u002Fdiv>\n\n[![Release Version](https:\u002F\u002Fimg.shields.io\u002Fmaven-central\u002Fv\u002Fio.mockk\u002Fmockk.svg?label=release)](https:\u002F\u002Fsearch.maven.org\u002F#search%7Cga%7C1%7Cmockk)\n[![Change log](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fchange%20log-%E2%96%A4-yellow.svg)](https:\u002F\u002Fgithub.com\u002Fmockk\u002Fmockk\u002Freleases)\n[![codecov](https:\u002F\u002Fcodecov.io\u002Fgh\u002Fmockk\u002Fmockk\u002Fbranch\u002Fmaster\u002Fgraph\u002Fbadge.svg)](https:\u002F\u002Fcodecov.io\u002Fgh\u002Fmockk\u002Fmockk)\n[![Android](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fandroid-support-green.svg)](https:\u002F\u002Fmockk.io\u002FANDROID)\n[![Matrix tests](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fmatrix-test-e53994.svg)](https:\u002F\u002Fmockk.io\u002FMATRIX)\n[![Open Source Helpers](https:\u002F\u002Fwww.codetriage.com\u002Fmockk\u002Fmockk\u002Fbadges\u002Fusers.svg)](https:\u002F\u002Fwww.codetriage.com\u002Fmockk\u002Fmockk)\n\n## Getting started\n\nAll you need to get started is just to add a dependency to `MockK` library.\n\n#### Gradle\u002FMaven dependency\n\n\u003Ctable>\n\u003Cthead>\u003Ctr>\u003Cth>Approach\u003C\u002Fth>\u003Cth>Instruction\u003C\u002Fth>\u003C\u002Ftr>\u003C\u002Fthead>\n\u003Ctr>\n\u003Ctd>\u003Cimg src=\"doc\u002Fgradle.png\" alt=\"Gradle\"\u002F>\u003C\u002Ftd>\n\u003Ctd>\n\u003Cpre>\ntestImplementation \"io.mockk:mockk:${mockkVersion}\"\n\u003C\u002Fpre>\n\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\u003Cimg src=\"doc\u002Fgradle.png\" alt=\"Gradle\"\u002F> (Kotlin DSL)\u003C\u002Ftd>\n \u003Ctd>\n  \u003Cpre>testImplementation(\"io.mockk:mockk:${mockkVersion}\")\u003C\u002Fpre>\n \u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\u003Cimg src=\"doc\u002Fmaven.png\" alt=\"Maven\"\u002F>\u003C\u002Ftd>\n\u003Ctd>\n\u003Cpre>\n &lt;dependency&gt;\n     &lt;groupId&gt;io.mockk&lt;\u002FgroupId&gt;\n     &lt;artifactId&gt;mockk-jvm&lt;\u002FartifactId&gt;\n     &lt;version&gt;${mockkVersion}&lt;\u002Fversion&gt;\n     &lt;scope&gt;test&lt;\u002Fscope&gt;\n &lt;\u002Fdependency&gt;\n\u003C\u002Fpre>\n\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\u003Ca href=\"ANDROID.html\">\u003Cimg align=\"top\" src=\"doc\u002Frobot-small.png\" height=\"20\" alt=\"android\"\u002F> Unit\u003C\u002Fa>\u003C\u002Ftd>\n\u003Ctd>\n\u003Cpre>\ntestImplementation \"io.mockk:mockk-android:${mockkVersion}\"\ntestImplementation \"io.mockk:mockk-agent:${mockkVersion}\"\n\u003C\u002Fpre>\n\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\u003Ca href=\"ANDROID.html\">\u003Cimg align=\"top\" src=\"doc\u002Frobot-small.png\" height=\"20\" alt=\"android\"\u002F> Instrumented\u003C\u002Fa>\u003C\u002Ftd>\n\u003Ctd>\n\u003Cpre>\nandroidTestImplementation \"io.mockk:mockk-android:${mockkVersion}\"\nandroidTestImplementation \"io.mockk:mockk-agent:${mockkVersion}\"\n\u003C\u002Fpre>\n\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003C\u002Ftable>\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>()\n\nevery { car.drive(Direction.NORTH) } returns Outcome.OK\n\ncar.drive(Direction.NORTH) \u002F\u002F returns OK\n\nverify { car.drive(Direction.NORTH) }\n\nconfirmVerified(car)\n```\n\nSee the \"Features\" section below for more detailed examples.\n\n## BDD style (optional)\n\nFor teams using Behavior-Driven Development, MockK provides BDD-style aliases\n\n```gradle\ntestImplementation \"io.mockk:mockk:${mockkVersion}\"\ntestImplementation \"io.mockk:mockk-bdd:${mockkVersion}\"\n```\n\n```gradle\nandroidTestImplementation \"io.mockk:mockk-android:${mockkVersion}\"\nandroidTestImplementation \"io.mockk:mockk-bdd-android:${mockkVersion}\"\n```\n\n### BDD aliases\n\n| Standard MockK | BDD style |\n|----------------|-----------|\n| `every { ... }` | `given { ... }` |\n| `coEvery { ... }` | `coGiven { ... }` |\n| `verify { ... }` | `then { ... }` |\n| `coVerify { ... }` | `coThen { ... }` |\n\n\n### Spring support\n\n * [springmockk](https:\u002F\u002Fgithub.com\u002FNinja-Squad\u002Fspringmockk) introduced in official [Spring Boot Kotlin tutorial](https:\u002F\u002Fspring.io\u002Fguides\u002Ftutorials\u002Fspring-boot-kotlin\u002F)\n\n### Quarkus support\n\n * [quarkus-mockk](https:\u002F\u002Fgithub.com\u002Fquarkiverse\u002Fquarkus-mockk) adds support for mocking beans in Quarkus. Documentation can be found [here](https:\u002F\u002Fquarkiverse.github.io\u002Fquarkiverse-docs\u002Fquarkus-mockk\u002Fdev\u002Findex.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:\u002F\u002Fgithub.com\u002Fmockk\u002Fmockk\u002Fissues\u002F79#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:\u002F\u002Fgithub.com\u002Fmockk\u002Fmockk\u002Fissues\u002F27)\n* Spies, `mockkStatic` may not work on JDK 16+; `InaccessibleObjectException`\u002F`IllegalAccessException`: [read more here](doc\u002Fmd\u002Fjdk16-access-exceptions.md)\n* Using a spy with a suspending function [will give unexpected test results](https:\u002F\u002Fgithub.com\u002Fmockk\u002Fmockk\u002Fissues\u002F554)\n\nTable of contents:\n\n* auto-gen TOC:\n{:toc}\n\n## Examples, guides & articles\n\n### Kotlin Academy articles \u003Cimg src=\"https:\u002F\u002Fcdn-images-1.medium.com\u002Fletterbox\u002F47\u002F47\u002F50\u002F50\u002F1*FUXqI88mttV_kV8aTrKjOg.png?source=logoAvatar-1f9f77b4b3d1---e57b304801ef\" width=\"20px\" \u002F>\n\nCheck the series of articles \"Mocking is not rocket science\" at [Kt. Academy](https:\u002F\u002Fblog.kotlin-academy.com) describing MockK from the very basics of mocking up to description of all advanced features.\n\n - [Basics](https:\u002F\u002Fblog.kotlin-academy.com\u002Fmocking-is-not-rocket-science-basics-ae55d0aadf2b)\n - [Expected behavior and behavior verification](https:\u002F\u002Fblog.kotlin-academy.com\u002Fmocking-is-not-rocket-science-expected-behavior-and-behavior-verification-3862dd0e0f03)\n - [MockK features](https:\u002F\u002Fblog.kotlin-academy.com\u002Fmocking-is-not-rocket-science-mockk-features-e5d55d735a98)\n - [MockK advanced features](https:\u002F\u002Fblog.kotlin-academy.com\u002Fmocking-is-not-rocket-science-mockk-advanced-features-42277e5983b5)\n\n - [Testing Quarkus with Kotlin, JUnit and MockK](https:\u002F\u002Fwww.novatec-gmbh.de\u002Fen\u002Fblog\u002Ftesting-quarkus-with-kotlin-junit-and-mockk\u002F)\n - [Unraveling MockK's black magic(EN, translation)](https:\u002F\u002Fchao2zhang.medium.com\u002Funraveling-mockks-black-magic-e725c61ed9dd)\n - [Mockk Guidebook](https:\u002F\u002Fnotwoods.github.io\u002Fmockk-guidebook\u002F)\n - [“Kotlin Unit Testing with Mockk” by Marco Cattaneo](https:\u002F\u002Flink.medium.com\u002FObtQ4eBfg5)\n - [(Video) Use verify in MockK to validate function calls on mocked object](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=J7_4WrImJPk)\n - [Testing With MockK paid course on raywenderlich.com](https:\u002F\u002Fwww.raywenderlich.com\u002F5443751-testing-with-mockk)\n - TDD for Android video tutorial [part 1](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=60KFJTb_HwU), [part 2](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=32pnzGirvgM) by Ryan Kay\n - [(Video)Android Developer Live Coding #13: Unit Testing with Mockk, Coroutines, Test Driven Development](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=h8_LZn1DFDI)\n - [KotlinConf 2018 - Best Practices for Unit Testing in Kotlin by Philipp Hauer](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=RX_g65J14H0&feature=youtu.be&t=940)\n - [kotlin-fullstack-sample uses MockK](https:\u002F\u002Fgithub.com\u002FKotlin\u002Fkotlin-fullstack-sample\u002Fpull\u002F28\u002Ffiles#diff-eade18fbfd0abfb6338dbfa647b3215dR17) project covered with tests\n - [DZone article](https:\u002F\u002Fdzone.com\u002Farticles\u002Fnew-mocking-tool-for-kotlin-an-alternative-to-java)\n - [Habrahabr article](https:\u002F\u002Fhabrahabr.ru\u002Fpost\u002F341202\u002F) (RU)\n - [Mocking in Kotlin with MockK - Yannick De Turck](https:\u002F\u002Fordina-jworks.github.io\u002Ftesting\u002F2018\u002F02\u002F05\u002FWriting-tests-in-Kotlin-with-MockK.html)\n - [How does MockK work internally? - Sagar Malhotra](https:\u002F\u002Fproandroiddev.com\u002Fhow-does-mocking-work-internally-a-deep-dive-into-mockk-internals-defecd66b815)\n\n### Japanese guides and articles\n - [Documentation translation to Japanese](https:\u002F\u002Fqiita.com\u002FyasuX\u002Fitems\u002Fd3cfc9853c53dfaee222)\n - [Unraveling MockK's black magic \u002F MockKの「黒魔術」を解明する (JP, but readable through chrome translator)](https:\u002F\u002Fzenn.dev\u002Foboenikui\u002Farticles\u002Faf44c158f9fa35)\n\n### Chinese guides and articles\n - [用 Kotlin + Mockito 寫單元測試會碰到什麼問題？](https:\u002F\u002Fmedium.com\u002Fjoe-tsai\u002Fmockk-%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:\u002F\u002Fmedium.com\u002Fjoe-tsai\u002Fmockk-%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:\u002F\u002Fmedium.com\u002Fjoe-tsai\u002Fmockk-%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:\u002F\u002Fmedium.com\u002Fjoe-tsai\u002Fmockk-%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:\u002F\u002Fwww.devkuma.com\u002Fdocs\u002Fkotlin\u002Fmockk\u002F)\n - [MockK의 흑마술을 파헤치자!](https:\u002F\u002Fsukyology.medium.com\u002Fmockk%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) \u002F\u002F turn relaxUnitFun on for all mocks\n\n  @Test\n  fun calculateAddsValues1() {\n      \u002F\u002F ... 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### @InjectMockKs dependency order\n\nIf multiple `@InjectMockKs` properties depend on each other via constructor parameters, initialization order matters.\nBy default, MockK processes them in reflection order; to resolve dependencies deterministically, enable dependency\norder:\n\n```kotlin\n@Before\nfun setUp() = MockKAnnotations.init(this, useDependencyOrder = true)\n```\n\nThis applies a topological sort across `@InjectMockKs` and throws `MockKException` on circular dependencies.\nEnabling `useDependencyOrder` adds an approximate 3-5% performance overhead during initialization.\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     \u002F\u002F 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      \u002F\u002F ... 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  \u002F\u002F ... 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#### Declarative enabling of dependency order\n\nYou can enable topological dependency resolution of `@InjectMockKs` by also annotating your test class with `@MockKExtension.UseDependencyOrder`.\n\nThis will internally process each test instance of the annotated class with `MockKAnnotations.init(useDependencyOrder==true)`.\n\n### Spy\n\nSpies allow you to mix mocks and real objects.\n\n```kotlin\nval car = spyk(Car()) \u002F\u002F or spyk\u003CCar>() to call the default constructor\n\ncar.drive(Direction.NORTH) \u002F\u002F 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:\u002F\u002Fgithub.com\u002Fmockk\u002Fmockk\u002Fissues\u002F554\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>(relaxed = true)\n\ncar.drive(Direction.NORTH) \u002F\u002F 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() -> Car>(relaxed = true) \u002F\u002F in this case invoke function has generic return type\n\n\u002F\u002F this line is workaround, without it the relaxed mock would throw a class cast exception on the next line\nevery { func() } returns Car() \u002F\u002F 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>()\n\nevery { adder.addOne(any()) } returns -1\nevery { adder.addOne(3) } answers { callOriginal() }\n\nassertEquals(-1, adder.addOne(2))\nassertEquals(4, adder.addOne(3)) \u002F\u002F 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>(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) \u002F\u002F 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    \u002F\u002F 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>()\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) \u002F\u002F 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>().add(1, 2) } returns 4\n\nassertEquals(4, MockCls().add(1, 2)) \u002F\u002F note new object is created\n\nverify { anyConstructed\u003CMockCls>().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>()`.\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>().add(1) } returns 2\nevery {\n    constructedWith\u003CMockCls>(OfTypeMatcher\u003CString>(String::class)).add(2) \u002F\u002F Mocks the constructor which takes a String\n} returns 3\nevery {\n    constructedWith\u003CMockCls>(EqMatcher(4)).add(any()) \u002F\u002F 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>().add(1)\n    constructedWith\u003CMockCls>(OfTypeMatcher\u003CString>(String::class)).add(2)\n    constructedWith\u003CMockCls>(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`.\nThis means that when verifying invocations on a `prototype mock` you have to ensure that the argument matchers used are\nthe same that where used when stubbing, i.e. the matchers in the `verify` block and in the `every` block must be the\nsame.\n\nWhen constructor arguments are mocks, prefer `SameInstanceMatcher` (reference match) and reuse the same matcher\ninstances in both `every` and `verify`:\n\n```kotlin\nmockkConstructor(Intent::class)\n\nval uri = mockk\u003CUri>()\nval uriMatcher = SameInstanceMatcher(uri)\n\nevery {\n    constructedWith\u003CIntent>(EqMatcher(Intent.ACTION_VIEW), uriMatcher).setFlags(any())\n} returns mockk()\n\nverify {\n    constructedWith\u003CIntent>(EqMatcher(Intent.ACTION_VIEW), uriMatcher).setFlags(any())\n}\n```\n\n\n### Partial argument matching\n\nYou can mix both regular arguments and matchers:\n\n```kotlin\nval car = mockk\u003CCar>()\n\nevery {\n  car.recordTelemetry(\n    speed = more(50),\n    direction = Direction.NORTH, \u002F\u002F 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>()\n\nevery { car.door(DoorType.FRONT_LEFT).windowState() } returns WindowState.UP\n\ncar.door(DoorType.FRONT_LEFT) \u002F\u002F returns chained mock for Door\ncar.door(DoorType.FRONT_LEFT).windowState() \u002F\u002F 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>\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> {\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?>()` 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>()\n\u002F\u002F allow to capture parameter with non nullable type `Double`\nval speedSlot = slot\u003CDouble>()\n\u002F\u002F allow to capture parameter with nullable type `RoadType`\nval roadTypeSlot = slot\u003CRoadType?>()\nval list = mutableListOf\u003CDouble>()\n\nevery {\n    car.recordTelemetry(\n        speed = capture(speedSlot), \u002F\u002F makes mock match calls with any value for `speed` and record it in a slot\n        direction = Direction.NORTH, \u002F\u002F makes mock and capturing only match calls with specific `direction`. Use `any()` to match calls with any `direction`\n        roadType = captureNullable(roadTypeSlot), \u002F\u002F 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) \u002F\u002F prints Speed: 15.0, roadType: null\ncar.recordTelemetry(speed = 16.0, direction = Direction.SOUTH, RoadType.HIGHWAY) \u002F\u002F 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>(relaxed = true)\n\ncar.accelerate(fromSpeed = 10, toSpeed = 20)\ncar.accelerate(fromSpeed = 10, toSpeed = 30)\ncar.accelerate(fromSpeed = 20, toSpeed = 30)\n\n\u002F\u002F 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) } \u002F\u002F means no calls were performed\n\nconfirmVerified(car)\n```\n\nOr you can use `verifyCount`:\n\n```kotlin\n\nval car = mockk\u003CCar>(relaxed = true)\n\ncar.accelerate(fromSpeed = 10, toSpeed = 20)\ncar.accelerate(fromSpeed = 10, toSpeed = 30)\ncar.accelerate(fromSpeed = 20, toSpeed = 30)\n\n\u002F\u002F all pass\nverifyCount {\n    (3..5) * { car.accelerate(allAny(), allAny()) } \u002F\u002F same as verify(atLeast = 3, atMost = 5) { car.accelerate(allAny(), allAny()) }\n    1 * { car.accelerate(fromSpeed = 10, toSpeed = 20) } \u002F\u002F same as verify(exactly = 1) { car.accelerate(fromSpeed = 10, toSpeed = 20) }\n    0 * { car.accelerate(fromSpeed = 30, toSpeed = 10) } \u002F\u002F 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>()\nval slot = slot\u003CInt>()\n\nevery {\n    obj.sum(any(), capture(slot))\n} answers {\n    1 + firstArg\u003CInt>() + slot.captured\n}\n\nobj.sum(1, 2) \u002F\u002F returns 4\nobj.sum(1, 3) \u002F\u002F returns 5\nobj.sum(2, 2) \u002F\u002F 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>()\nval obj3 = mockk\u003CMockedClass>()\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\nSince v1.14.6 you can pass `clear = true` to also clear verification marks and recorded calls for the provided mocks after confirmation.\n\n```kotlin\nconfirmVerified(mock1, mock2, clear = true)\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>()\n\nevery { car.drive(Direction.NORTH) } returns Outcome.OK\nevery { car.drive(Direction.SOUTH) } returns Outcome.OK\n\ncar.drive(Direction.NORTH) \u002F\u002F returns OK\ncar.drive(Direction.SOUTH) \u002F\u002F returns OK\n\nverify {\n    car.drive(Direction.SOUTH)\n    car.drive(Direction.NORTH)\n}\n\nconfirmVerified(car) \u002F\u002F makes sure all calls were covered with verification\nconfirmVerified(car, clear = true) \u002F\u002F makes sure all calls were covered with verification and clears verification marks and recorded calls\n```\n\n### Unnecessary stubbing\n\nBecause clean & 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>()\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) \u002F\u002F returns OK\ncar.drive(Direction.SOUTH) \u002F\u002F returns OK\n\nverify {\n    car.drive(Direction.NORTH)\n}\n\nconfirmVerified(car) \u002F\u002F 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> {\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>()\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>\n\u003Ctr>\n    \u003Cth>Gradle\u003C\u002Fth>\n\u003C\u002Ftr>\n\u003Ctr>\n    \u003Ctd>\n\u003Cpre>testImplementation \"org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x\"\u003C\u002Fpre>\n    \u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003C\u002Ftable>\n\u003Ctable>\n\u003Ctr>\n    \u003Cth>Maven\u003C\u002Fth>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\n    \u003Cpre>\n&lt;dependency&gt;\n    &lt;groupId&gt;org.jetbrains.kotlinx&lt;\u002FgroupId&gt;\n    &lt;artifactId&gt;kotlinx-coroutines-core&lt;\u002FartifactId&gt;\n    &lt;version&gt;x.x&lt;\u002Fversion&gt;\n    &lt;scope&gt;test&lt;\u002Fscope&gt;\n&lt;\u002Fdependency&gt;\u003C\u002Fpre>\n    \u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003C\u002Ftable>\n\nThen you can use `coEvery`, `coVerify`, `coMatch`, `coAssert`, `coRun`, `coAnswers` or `coInvoke` to mock suspend functions.\n\n```kotlin\nval car = mockk\u003CCar>()\n\ncoEvery { car.drive(Direction.NORTH) } returns Outcome.OK\n\ncar.drive(Direction.NORTH) \u002F\u002F 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>()\n\n    coJustAwait { car.drive(any()) } \u002F\u002F 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() \u002F\u002F 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:\u002F\u002Fgithub.com\u002Fmockk\u002Fmockk\u002Fissues\u002F554\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() }\nconfirmVerified(::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`confirmVerified` accepts function\u002Fproperty references, but scoped confirmation works only for references backed by static mocks (typically top-level or module-wide extension references used with `mockkStatic`).\nIf you pass `clear = true` to `confirmVerified` with function\u002Fproperty references, only selected references are cleared.\n`confirmVerified()` with no arguments keeps its original behavior and confirms all stubs.\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>()) {\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\u002F\u002F 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\u002F\u002F ... 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>()) } returns true\nprintln(File(\"abc\").endsWith(\"abc\"))\n```\nThis is standard Kotlin behaviour that may be unpredictable.\nUse `Tools -> Kotlin -> 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>()\n\nevery { obj.manyMany(5, 6, *varargAll { it == 7 }) } returns 3\n\nprintln(obj.manyMany(5, 6, 7)) \u002F\u002F 3\nprintln(obj.manyMany(5, 6, 7, 7)) \u002F\u002F 3\nprintln(obj.manyMany(5, 6, 7, 7, 7)) \u002F\u002F 3\n\nevery { obj.manyMany(5, 6, *anyVararg(), 7) } returns 4\n\nprintln(obj.manyMany(5, 6, 1, 7)) \u002F\u002F 4\nprintln(obj.manyMany(5, 6, 2, 3, 7)) \u002F\u002F 4\nprintln(obj.manyMany(5, 6, 4, 5, 6, 7)) \u002F\u002F 4\n\nevery { obj.manyMany(5, 6, *varargAny { nArgs > 5 }, 7) } returns 5\n\nprintln(obj.manyMany(5, 6, 4, 5, 6, 7)) \u002F\u002F 5\nprintln(obj.manyMany(5, 6, 4, 5, 6, 7, 7)) \u002F\u002F 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)) \u002F\u002F 6\nprintln(obj.manyMany(5, 6, 3, 4, 4, 7)) \u002F\u002F 6\n```\n\n### Private functions mocking \u002F 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>(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>() } 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\u002F\u002F 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### Suppressing superclass calls\n\nTo suppress a method call, especially a `super` call inside an overridden method, you can stub its behavior on a `spyk`.\nUsing `every { ... } just runs` replaces the entire method body, preventing the original code from executing.\n\nThis is particularly useful for users coming from frameworks like PowerMockito or for testing classes like Android Activities.\nFor reference, see [PowerMockito suppress documentation](https:\u002F\u002Fgithub.com\u002Fpowermock\u002Fpowermock\u002Fwiki\u002FSuppress-Unwanted-Behavior).\n\n```kotlin\n\u002F\u002F A simple inheritance hierarchy\nopen class Parent {\n    var superCalled = false\n    open fun doWork() {\n        superCalled = true\n    }\n}\n\nclass Child : Parent() {\n    override fun doWork() {\n        super.doWork() \u002F\u002F We want to suppress this call during testing\n    }\n}\n\n\u002F\u002F In your test:\nval child = spyk\u003CChild>()\n\n\u002F\u002F Stub the method: prevents the original (super) implementation from being invoked\nevery { child.doWork() } just runs\n\nchild.doWork()\n\n\u002F\u002F Verify that the superclass method was not executed\nassertFalse(child.superCalled)\n```\n\nThis approach allows you to isolate the logic within your method for unit testing without executing unwanted parent class behavior.\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>) = match\u003CSequence\u003CString>> {\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>) = a.reversed()\n    }\n\n    val mock = mockk\u003CMockCls>()\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>(\n    val expectedList: List\u003CT>,\n    val refEq: Boolean\n) : Matcher\u003CList\u003CT>> {\n    val map = buildCountsMap(expectedList, refEq)\n\n    override fun match(arg: List\u003CT>?): Boolean {\n        if (arg == null) return false\n        return buildCountsMap(arg, refEq) == map\n    }\n\n    private fun buildCountsMap(list: List\u003CT>, ref: Boolean): Map\u003CAny?, Int> {\n        val map = mutableMapOf\u003CAny?, Int>()\n\n        for (item in list) {\n            val key = when {\n                item == null -> nullKey\n                refEq -> InternalPlatform.ref(item)\n                else -> item\n            }\n            map.compute(key, { _, value -> (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>): Matcher\u003CList\u003CT>> {\n        return copy(expectedList = expectedList.map { map.getOrDefault(it as Any?, it) } as List\u003CT>)\n    }\n\n    companion object {\n        val nullKey = Any()\n    }\n}\n\ninline fun \u003Creified T : List\u003CE>, E : Any> 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> {\n  builderFunctions.forEach { func ->\n    every {\n      val params = listOf\u003CAny?>(builderMock) + func.parameters.drop(1).map { any(it.type.classifier as KClass\u003CAny>) }\n      func.call(*params.toTypedArray())\n    } answers {\n      this@mockk\n    }\n  }\n}\n```\n\n## Configuration File\n\nTo adjust parameters globally, you can specify settings in a configuration file.\n\n### How to use:\n\n1. Create the configuration file at `src\u002Ftest\u002Fresources\u002Fmockk.properties`.\n2. Add any of the following configuration options:\n\n```properties\n# MockK Settings\nrelaxed=true|false\nrelaxUnitFun=true|false\nrecordPrivateCalls=true|false\nstackTracesOnVerify=true|false\nstackTracesAlignment=left|center\nfailOnSetBackingFieldException=true|false\n\n# Restricted Mocking Configuration (see Restricted Mocking section below)\nmockk.restrictedClasses=com.example.MyClass,com.example.AnotherClass\nmockk.throwExceptionOnBadMock=true|false\n```\n\n### Configuration Options\n\n| **Property**                    | **Description**                                                                                 | **Default Value** |\n|---------------------------------|-------------------------------------------------------------------------------------------------|-------------------|\n| `relaxed`                       | Enable relaxed mocking globally                                                                 | `false`           |\n| `relaxUnitFun`                  | Enable relaxed mocking for Unit-returning functions                                             | `false`           |\n| `recordPrivateCalls`            | Record private calls for verification                                                           | `false`           |\n| `stackTracesOnVerify`           | Show stack traces on verification failures                                                      | `true`            |\n| `stackTracesAlignment`          | Align stack traces to `left` or `center`                                                        | `center`          |\n| `failOnSetBackingFieldException`| Fail tests if backing field cannot be set                                                       | `false`           |\n| `mockk.restrictedClasses`       | Add fully qualified names of classes to restrict from mocking (comma-separated)                 | N\u002FA               |\n| `mockk.throwExceptionOnBadMock` | Throw exception when mocking restricted classes (`true`), or log warning only (`false`)         | `false`           |\n\n**Notes:**\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` is set to `true`, tests fail if a backing field could not be set.\n Otherwise, only the warning \"Failed to set backing field\" will be logged.\n See [here](https:\u002F\u002Fgithub.com\u002Fmockk\u002Fmockk\u002Fissues\u002F1291) for more details.\n\n### Legacy Configuration\n\nFor backward compatibility, MockK also supports the legacy configuration file:\n```\nsrc\u002Ftest\u002Fresources\u002Fio\u002Fmockk\u002Fsettings.properties\n```\n\nIf both files exist, `mockk.properties` takes precedence. The legacy location is deprecated and will be removed in a future version.\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>(...)`           | builds a regular mock                                                                                      |\n| `spyk\u003CT>()`               | 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| `clearAllStubsFromMemory` | removes all mocks from the internal collection storing them, and as a result frees up memory.              |\n\n\n### Matchers\n\nBy default, simple arguments are matched using `eq()`\n\n| Matcher                                                 | Description                                                                                            |\n|---------------------------------------------------------|--------------------------------------------------------------------------------------------------------|\n| `any\u003CT>()`                                              | matches any argument of type `T` (type-checked)                                                        |\n| `any(Class)`                                            | matches any argument of the given Class (type-checked; useful 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                                                    ","MockK 是一个专为 Kotlin 设计的模拟库。它提供了强大的模拟功能，支持参数匹配、链式调用和行为定义等特性，使得单元测试更加灵活和高效。MockK 采用简洁的 DSL 风格语法，易于上手且功能强大，能够很好地满足 TDD（测试驱动开发）的需求。此外，MockK 还特别针对 Android 开发进行了优化，无论是单元测试还是仪器化测试都能良好支持。因此，对于使用 Kotlin 进行开发并希望提高测试代码质量的开发者来说，MockK 是一个非常实用的选择。","2026-06-11 03:11:21","top_language"]