### Configure Runtime Dependencies Repository Source: https://mokkery.dev/docs/Setup This Gradle configuration block specifies the repositories to use for downloading runtime dependencies. `mavenCentral()` is a common repository for many libraries. Ensure this is correctly set up if Mokkery dependencies are not found. ```gradle repositories { mavenCentral() } ``` -------------------------------- ### Configure Plugin Management Repository Source: https://mokkery.dev/docs/Setup This block configures repositories for Gradle plugins. `gradlePluginPortal()` is essential for discovering plugins, especially for Mokkery versions prior to 2.3.0. `mavenCentral()` is also included for broader plugin availability. ```gradle pluginManagement { repositories { gradlePluginPortal() // required only before Mokkery 2.3.0 mavenCentral() } } ``` -------------------------------- ### Apply Mokkery to All Source Sets Source: https://mokkery.dev/docs/Setup This configuration block enables Mokkery for all source sets within the current subproject. Use this if you need Mokkery in main source sets, for example, when extracting mocks to a separate subproject. This overrides the default test source set application. ```kotlin mokkery { rule.set(ApplicationRule.All) } ``` -------------------------------- ### Use Matchers for Broad Parameter Value Acceptance in Kotlin Source: https://mokkery.dev/docs/Quick_start Shows how to use matchers like `any()` to define behavior that accepts a wider range of parameter values for mocked functions. This is useful when the exact parameter value is not important, and a default response is desired for any input. ```kotlin every { foo.getAt(any()) } returns 0 foo.getAt(0) // returns 0 foo.getAt(1) // returns 0 foo.getAt(2) // returns 0 ``` -------------------------------- ### Create a Mock Object in Kotlin Source: https://mokkery.dev/docs/Quick_start Demonstrates how to create a mock object for a given type using the `mock` function. This is the foundational step for mocking in Mokkery. If a mocked member is called without defined behavior, a runtime error occurs. ```kotlin val foo = mock() ``` -------------------------------- ### Verify Function Calls in Kotlin Source: https://mokkery.dev/docs/Quick_start Demonstrates how to verify that specific function calls have occurred using the `verify` function. This is essential for ensuring that your code interacts with dependencies as expected. Each verification consumes unverified calls. ```kotlin verify { foo.getAll() } ``` -------------------------------- ### Apply Mokkery Gradle Plugin (Kotlin 2.3.10) Source: https://mokkery.dev/docs/Setup This snippet demonstrates applying the Mokkery Gradle plugin for Kotlin version 2.3.10. It includes the Kotlin multiplatform plugin and the Mokkery plugin. Always check for version compatibility between Mokkery and Kotlin. ```gradle plugins { kotlin("multiplatform") version "2.3.10" // ...or any other Kotlin plugin id("dev.mokkery") version "3.2.0" } ``` -------------------------------- ### Apply Mokkery to Listed Source Sets Source: https://mokkery.dev/docs/Setup This option allows you to manually specify which source sets Mokkery should be applied to. It's useful for fine-grained control over Mokkery's application scope. Ensure all necessary source sets within a subtree are included. ```kotlin ApplicationRule.Listed("fooMain", "barMain") ``` -------------------------------- ### Define Answers Using Function References Source: https://mokkery.dev/docs/Guides/Mocking Provides a shorthand for defining answers using function references (e.g., `foo::getAll`). This can make the mocking configuration more concise. ```kotlin every(foo::getAll) returns listOf(1, 2) // For property getters every(foo::values::get) returns listOf(2, 3) // For property setters every(foo::values::set) returns Unit // For suspending functions everySuspend(foo::fetchAt) returns 10 // Example calls demonstrating the defined answers foo.getAll() // returns listOf(1, 2) foo.values // returns listOf(2, 3) foo.values = emptyList() // returns Unit foo.fetchAt(0) // returns 10 foo.fetchAt(1) // returns 10 foo.fetchAt(2) // returns 10 ``` -------------------------------- ### Shorthand Behavior Definition with Function References in Kotlin Source: https://mokkery.dev/docs/Quick_start Provides a concise way to define behavior using function references with `every` and `everySuspend`. This syntax simplifies the definition of mocked function and property accessors, along with examples of how mocked calls return configured values. ```kotlin every(foo::getAll) returns listOf(1, 2) every(foo::values::get) returns listOf(2, 3) every(foo::values::set) returns Unit everySuspend(foo::fetchAt) returns 10 foo.getAll() // returns listOf(1, 2) foo.values // returns listOf(2, 3) foo.values = emptyList() // returns Unit foo.fetchAt(0) // returns 10 ``` -------------------------------- ### Configure Dependency Resolution Repositories Source: https://mokkery.dev/docs/Setup This configuration within `dependencyResolutionManagement` defines repositories for resolving project dependencies. It includes `mavenCentral()` and `gradlePluginPortal()`, the latter being crucial for Mokkery plugin resolution before version 2.3.0. ```gradle dependencyResolutionManagement { repositories { mavenCentral() // required to download Mokkery Gradle plugin before version 2.3.0 gradlePluginPortal() } } ``` -------------------------------- ### Configure Mock Behavior within a Mock Block in Kotlin Source: https://mokkery.dev/docs/Quick_start Demonstrates how to group multiple behavior configurations within a `mock` block. This approach enhances organization by defining mock creation and its associated behaviors together, including support for `autoUnit`. ```kotlin val mock = mock(autoUnit) { every { getAll() } returns listOf(1, 2, 3) everySuspend { fetchAll() } returns listOf(1, 2, 3) } ``` -------------------------------- ### Add Mokkery Gradle Plugin Dependency Source: https://mokkery.dev/docs/Setup This line adds the Mokkery Gradle plugin as an implementation dependency. Replace `$mokkeryVersion` with the actual version you are using. This ensures the plugin is available for your project. ```gradle dependencies { implementation("dev.mokkery:mokkery-gradle:$mokkeryVersion") } ``` -------------------------------- ### Kotlin Mocking Example with Mokkery Source: https://mokkery.dev/docs/index Demonstrates how to use Mokkery to mock a BookRepository and test a BookService. It shows setting up suspend functions with custom answers and verifying calls with `runTest` and `verifySuspend`. ```kotlin class BookServiceTest { val repository = mock { everySuspend { findById(any()) } calls { (id: String) -> Book(id) } } val service = BookService(repository) @Test fun `rent should call repository for each book`() = runTest { service.rentAll(listOf("1", "2")) verifySuspend(exhaustiveOrder) { repository.findById("1") repository.findById("2") } } } ``` -------------------------------- ### Define Answers for Specific Parameter Values Source: https://mokkery.dev/docs/Guides/Mocking Demonstrates how to provide different answers for a function based on its specific parameter values. If multiple answers match, the most recently defined one takes precedence. ```kotlin every { foo.getAt(0) } returns 1 every { foo.getAt(1) } returns 2 foo.getAt(0) // returns 1 foo.getAt(1) // returns 2 foo.getAt(2) // error - answer not defined ``` -------------------------------- ### Implement Answer Description for Debugging (Kotlin) Source: https://mokkery.dev/docs/Guides/Answers This example shows how to implement the `description()` function within a custom `Answer` to provide a human-readable explanation. This is beneficial for debugging, particularly when using `printMokkeryDebug`. The description should mirror the code usage. ```kotlin infix fun SuspendAnsweringScope.returnsDelayed(value: T) { answers(ReturnsDelayedAnswer(value)) } // ... private class ReturnsDelayedAnswer(private val value: T) : Answer { // ... override fun description() = "returnsDelayed $value" } ``` -------------------------------- ### Apply Mokkery Gradle Plugin (Kotlin 1.9.25) Source: https://mokkery.dev/docs/Setup This snippet shows how to apply the Mokkery Gradle plugin for Kotlin version 1.9.25. It requires the Kotlin multiplatform plugin and the Mokkery plugin itself. Ensure your Mokkery version is compatible with your Kotlin version. ```gradle plugins { kotlin("multiplatform") version "1.9.25" // ...or any other Kotlin plugin id("dev.mokkery") version "1.9.25-1.7.0" } ``` -------------------------------- ### Define Behavior for Member Functions in Kotlin Source: https://mokkery.dev/docs/Quick_start Shows how to define the return value for a regular member function using the `every` function. This allows you to control the output of mocked functions during tests. For properties, you can define behavior for their getters and setters. ```kotlin every { foo.getAll() } returns listOf(1, 2, 3) // For properties: every { foo.values } returns listOf(1, 2, 3) // getter every { foo.values = any() } returns Unit // setter ``` -------------------------------- ### Define Answer for Property Setter Source: https://mokkery.dev/docs/Guides/Mocking Demonstrates how to define the behavior for a property's setter using the `every` block. This specifies what happens when a value is assigned to the property. ```kotlin every { foo.values = any() } returns Unit ``` -------------------------------- ### Mock Member Functions with Context Parameters in Kotlin Source: https://mokkery.dev/docs/Quick_start Explains how to mock member functions that utilize context parameters by using the special `ctx` function. This allows for mocking functions that depend on a specific context, requiring the import of `dev.mokkery.templating.ctx`. ```kotlin import dev.mokkery.templating.ctx // ... every { ctx(any()) { foo.getAllWithContext() } } returns listOf(1, 2, 3) context(FooContext()) { foo.getAllWithContext() // returns listOf(1, 2, 3) } ``` -------------------------------- ### Define Behavior for Specific Parameter Values in Kotlin Source: https://mokkery.dev/docs/Quick_start Explains how to specify return values for a mocked function based on its exact parameter values. If a call does not match any defined parameter-specific behavior, an error will occur. This allows for precise control over function responses. ```kotlin every { foo.getAt(0) } returns 1 every { foo.getAt(1) } returns 2 foo.getAt(0) // returns 1 foo.getAt(1) // returns 2 foo.getAt(2) // error - answer not defined ``` -------------------------------- ### Configure Mock Behavior with Autofill Mode Source: https://mokkery.dev/docs/Guides/Mocking Demonstrates creating a mock object using autofill mode. Autofill mode provides default empty values (e.g., 0 for numbers, "" for strings, null for complex types) for undefined behaviors. ```kotlin import dev.mokkery.MockMode.autofill val foo = mock(autofill) ``` -------------------------------- ### Define Answer for Property Getter Source: https://mokkery.dev/docs/Guides/Mocking Shows how to define the return value for a property's getter using the `every` block. This controls the value returned when the property is accessed. ```kotlin every { foo.values } returns listOf(1, 2, 3) ``` -------------------------------- ### Apply Mokkery to Source Sets Matching Regex Source: https://mokkery.dev/docs/Setup This custom rule applies Mokkery to source sets whose names match a given regular expression. This provides flexibility in defining the scope of Mokkery's application based on naming conventions. Remember to include all relevant source sets. ```kotlin ApplicationRule.MatchesName(Regex(".+Main")) ``` -------------------------------- ### Define Answer for Regular Member Function Source: https://mokkery.dev/docs/Guides/Mocking Illustrates how to define a specific return value for a regular member function call using the `every` block. This allows controlling the output of mocked functions. ```kotlin every { foo.getAll() } returns listOf(1, 2, 3) ``` -------------------------------- ### Configure Mock Behavior with Original Mode Source: https://mokkery.dev/docs/Guides/Mocking Shows how to create a mock object in original mode. This mode attempts to call the super implementation if available; otherwise, it fails. It's useful for types with default behavior. ```kotlin import dev.mokkery.MockMode.original val foo = mock(original) ``` -------------------------------- ### Configure Mock Behavior with Strict Mode Source: https://mokkery.dev/docs/Guides/Mocking Shows how to create a mock object that operates in strict mode. In strict mode, any call to a member function or property without a defined behavior will result in a runtime exception. ```kotlin import dev.mokkery.MockMode.strict val foo = mock(strict) ``` -------------------------------- ### Mock Member Functions with Extension Parameters in Kotlin Source: https://mokkery.dev/docs/Quick_start Details how to mock member functions that have extension parameters using the special `ext` function. This is necessary because standard `every` syntax does not support mocking extension parameters directly. It requires importing `dev.mokkery.templating.ext`. ```kotlin import dev.mokkery.templating.ext // ... every { foo.ext { any().toNumber() } } returns 10 foo.run { "10".toNumber() } // returns 10 ``` -------------------------------- ### Conditionally Apply all-open Plugin for Testing Source: https://mokkery.dev/docs/Guides/Mocking This code snippet demonstrates how to conditionally apply the `all-open` plugin configuration only when a testing task is executed. This prevents opening classes in production artifacts, which could be problematic for library consumers. ```kotlin // this check might require adjustment depending on your project type and the tasks that you use // `endsWith("Test")` works with "*Test" tasks from Multiplafrom projects, but it does not include tasks like `check` fun isTestingTask(name: String) = name.endsWith("Test") val isTesting = gradle .startParameter .taskNames .any(::isTestingTask) if (isTesting) allOpen { /* ... */ } ``` -------------------------------- ### Configure Mock Behavior with AutoUnit Mode Source: https://mokkery.dev/docs/Guides/Mocking Illustrates creating a mock object in autoUnit mode. This mode is similar to strict mode but does not throw an exception for Unit-returning functions that lack defined behavior. ```kotlin import dev.mokkery.MockMode.autoUnit val foo = mock(autoUnit) ``` -------------------------------- ### Soft Mode Verification Behavior in Kotlin Source: https://mokkery.dev/docs/Quick_start Explains the default soft mode verification in Mokkery, where each check verifies if a call pattern occurred at least once. In this mode, duplicated patterns within `verify` do not change the outcome, as each check is independent and successful if the pattern matched any call. ```kotlin foo.getAt(1) verify { foo.getAt(1) } // ✅ verify { foo.getAt(1) } // ❌ - no matching calls (consumed by first verify) foo.getAll() foo.getAll() verify { foo.getAll() } // ✅ - `getAll` was called at least once ``` -------------------------------- ### Manual Scope Creation with MokkerySuiteScope Source: https://mokkery.dev/docs/Guides/Strict_exhaustiveness Provides an example of manually creating a MokkerySuiteScope instance using `with` if the test class cannot be directly marked with the interface. This allows for stricter verification in such scenarios. ```kotlin with(MokkerySuiteScope()) { val a = mock() val b = mock() a.call(1) b.call(2) // Verification fails // Unverified call: b.call(2) verify(exhaustive) { a.call(1) } } ``` -------------------------------- ### Enable Mocking for Final Classes with all-open Plugin Source: https://mokkery.dev/docs/Guides/Mocking This section details how to make final classes mockable by applying the `all-open` Kotlin plugin. It involves applying the plugin, defining a custom annotation, annotating the target classes, and configuring the plugin to recognize the custom annotation. ```kotlin plugins { // ... kotlin("plugin.allopen") } ``` ```kotlin package your.package annotation class OpenForMokkery() ``` ```kotlin @OpenForMokkery class Foo { fun foo() = Unit } ``` ```kotlin allOpen { annotation("your.package.OpenForMokkery") } ``` -------------------------------- ### Set Default Mock Mode Globally Source: https://mokkery.dev/docs/Guides/Mocking Explains how to change the default mock mode for all subsequent mocks using the `defaultMockMode.set()` function within the `mokkery` configuration block. ```kotlin import dev.mokkery.MockMode mokkery { defaultMockMode.set(MockMode.autoUnit) } ``` -------------------------------- ### Handle Overlapping Answers with Precedence Source: https://mokkery.dev/docs/Guides/Mocking Illustrates how Mokkery handles cases where multiple defined answers could match a function call. The later defined answer takes precedence. ```kotlin // This answer is unreachable as the later defined matches all possible calls every { foo.getAt(0) } returns 1 every { foo.getAt(any()) } returns 2 foo.getAt(0) // returns 2 ``` -------------------------------- ### Create Custom Mokkery Answers Source: https://mokkery.dev/docs/index Implement custom answers for Mokkery mocks, supporting both blocking and suspending functions. Examples include generating random integers and returning a value after a delay. ```kotlin // Custom answer for blocking functions! fun BlockingAnsweringScope.randomInt() = calls { Random.nextInt() } // Custom answer for suspending functions! infix fun SuspendAnsweringScope.returnsDelayed(value: T) = calls { delay(1_000) value } ``` -------------------------------- ### Custom Suspend-Only Answer Extension in Mokkery Source: https://mokkery.dev/docs/Guides/Answers Provides an example of creating a custom answer extension function, `returnsDelayed`, specifically for `SuspendAnsweringScope`. This ensures that suspend-only answers are only used in the correct context, preventing compilation errors. ```kotlin infix fun SuspendAnsweringScope.returnsDelayed(value: T) { answers(ReturnsDelayedAnswer(value)) } // you can optionally mark this class as private private class ReturnsDelayedAnswer(private val value: T) : Answer { public fun call(scope: MokkeryBlockingCallScope): T = error("Not supported") public suspend fun call(scope: MokkerySuspendCallScope): T { delay(1_000) return value } } // Usage: everySuspend { mock.fetchAt(any()) } returnsDelayed 10 // ✅ compiles - suspend context every { mock.getAt(any()) } returnsDelayed 10 // ❌ does NOT compile - regular context ``` -------------------------------- ### Reset All Defined Answers for a Mock Source: https://mokkery.dev/docs/Guides/Mocking Explains how to reset all previously defined answers for a mock object using the `resetAnswers` function. After resetting, calls to the mock's members will behave according to the current mock mode. ```kotlin every { foo.getAt(0) } returns 1 resetAnswers(mock) foo.getAt(0) // error - answer not defined ``` -------------------------------- ### Configure Annotation Copying Behavior in Mokkery Source: https://mokkery.dev/docs/Guides/Mocking This configuration allows fine-grained control over which annotations are copied from a mocked type to its implementation. Various selectors like `all`, `none`, `named`, and `matches` can be used to define custom annotation copying rules. ```kotlin import dev.mokkery.options.AnnotationSelector.Companion.all import dev.mokkery.options.AnnotationSelector.Companion.none import dev.mokkery.options.AnnotationSelector.Companion.named import dev.mokkery.options.AnnotationSelector.Companion.matches mokkery { annotations { // No annotations copyToMock = none // All annotations except "example.A" copyToMock = all - named("example.A") // Only "example.A" copyToMock = named("example.A") // All annotations matching the regex "internal.*" copyToMock = matches(Regex("internal.*\\")) // Combine rules: all except "example.A" and all annotations starting with "internal" copyToMock = all - named("example.A") - matches(Regex("internal.*\\")) } } ``` -------------------------------- ### Synchronized Side Effect Handling in Mokkery (Kotlin) Source: https://mokkery.dev/docs/Thread_safety Demonstrates how to handle non-synchronized side effects in Mokkery mock configurations. The first example shows a potential issue with a simple increment, while the second uses atomic-fu for thread-safe synchronization. ```kotlin var x: Int = 0 every { mock.getAndIncrement() } calls { x++ } ``` ```kotlin var x = atomic(0) every { mock.getAndIncrement() } calls { x.getAndIncrement() } ``` -------------------------------- ### Define Behavior for Suspending Functions in Kotlin Source: https://mokkery.dev/docs/Quick_start Illustrates how to define the return value for a suspending member function using `everySuspend`. This is crucial for mocking asynchronous operations. Note that `everySuspend` itself is not a suspending function, allowing configuration in non-suspending contexts. ```kotlin everySuspend { foo.fetchAll() } returns listOf(1, 2, 3) ``` -------------------------------- ### Custom Answer Extension for Both Contexts in Mokkery Source: https://mokkery.dev/docs/Guides/Answers Demonstrates how to create a reusable custom answer extension, `returns`, that works for both regular and suspend functions by using `AnsweringScope` as the receiver. This promotes consistency when an answer is valid in both contexts. ```kotlin infix fun AnsweringScope.returns(value: T) { answers(ReturnsAnswer(value)) } private class ReturnsAnswer(private val value: T) : Answer { public fun call(scope: MokkeryBlockingCallScope): T = value public suspend fun call(scope: MokkerySuspendCallScope): T = value } // Usage: everySuspend { mock.fetchAt(any()) } returns 10 // suspend every { mock.getAt(any()) } returns 10 // regular // ✅ both compile ``` -------------------------------- ### Setting up Mokkery Coroutines Module Source: https://mokkery.dev/docs/Guides/Coroutines Provides instructions on how to add the `mokkery-coroutines` module to your project's dependencies. It shows both the direct Gradle dependency declaration and the usage of the Mokkery Gradle plugin utility. ```kotlin dependencies { implementation("dev.mokkery:mokkery-coroutines:$version") } ``` ```kotlin import dev.mokkery.gradle.mokkery dependencies { implementation(mokkery("coroutines")) // defaults to the current Mokkery version } ``` -------------------------------- ### Verify Suspending Function Calls in Kotlin Source: https://mokkery.dev/docs/Quick_start Shows how to verify calls to suspending functions using `verifySuspend`. Similar to `verify`, this function checks if a suspending function was invoked. It also consumes unverified calls, meaning repeated verifications might yield different results. ```kotlin verifySuspend { foo.fetchAll() } ``` -------------------------------- ### Combine Matchers with Logical Operators in Mokkery Source: https://mokkery.dev/docs/Guides/Matchers Demonstrates how to combine regular matchers using logical operators like 'or' and 'not' to create complex matching conditions for mock method calls. This allows for more nuanced control over when a mock should return a specific value. ```kotlin every { mock.getAt(or(1, not(2))) } returns 10 ``` -------------------------------- ### Define Constant Answer with `returns` Source: https://mokkery.dev/docs/Guides/Answers Use the `returns` keyword to define a constant value that the mock will return. This is the simplest way to set a mock's response. ```kotlin every { mock.getAt(index = any()) } returns 100 ``` -------------------------------- ### Shorthand for Sequential Returns with `sequentiallyReturns` Source: https://mokkery.dev/docs/Guides/Answers Use `sequentiallyReturns` with a list to define a simple sequence of return values. Calls beyond the list will fail. ```kotlin every { mock.getAt(any()) } sequentiallyReturns listOf(0, 1) ``` -------------------------------- ### Shorthand for Repeating Sequences with `sequentiallyRepeat` Source: https://mokkery.dev/docs/Guides/Answers The `sequentiallyRepeat` function provides a more concise way to define a sequence of answers that should repeat indefinitely. ```kotlin every { mock.getAt(any()) } sequentiallyRepeat { returns(0) returns(1) } ``` -------------------------------- ### Basic Mocking Without Strict Exhaustiveness Source: https://mokkery.dev/docs/Guides/Strict_exhaustiveness Demonstrates a basic test case using Mokkery mocks without enabling strict exhaustiveness checks. This example shows how verification only considers mocks within the verify block. ```kotlin class ClassTest { private val a = mock() private val b = mock() @Test fun test() { a.call(1) b.call(2) // Verification passes verify(exhaustive) { a.call(1) } } } ``` -------------------------------- ### Return `Result.success` with `returnsSuccess` Source: https://mokkery.dev/docs/Guides/Answers Specifically for functions returning `Result`, `returnsSuccess` simplifies returning a successful `Result` with a predefined value. ```kotlin every { mock.getAtCatching(index = 0) } returnsSuccess 1 ``` -------------------------------- ### Configure Default Verify Mode in Gradle Source: https://mokkery.dev/docs/Guides/Verifying Set the default verification mode for all Mokkery verifications in your `build.gradle` file. This allows you to enforce a specific verification strategy across your project without repeating it for each `verify` call. ```gradle import dev.mokkery.verify.VerifyMode.exhaustiveOrder mokkery { defaultVerifyMode.set(exhaustiveOrder) } ``` -------------------------------- ### Extend Answer with Existing Answers (Kotlin) Source: https://mokkery.dev/docs/Guides/Answers This snippet demonstrates how to declare an extension using existing built-in answers to create a custom answer without implementing a new `Answer` interface. It utilizes the `calls` block to define the behavior, including a delay. ```kotlin fun SuspendAnsweringScope.returnsDelayed(value: T) { calls { delay(1_000) value } } ``` -------------------------------- ### Super Calls API in Mokkery's 'calls' Scope Source: https://mokkery.dev/docs/Guides/Answers Illustrates the usage of the Super calls API within the `calls` scope in Mokkery. It shows how to invoke original implementations, call with specific arguments, and call superclass implementations. ```kotlin every { mock.getAt(any()) } calls { callOriginal() callOriginalWith(3) callSuper(BaseFoo::class) callSuperWith(BaseFoo::class, 3) } ``` -------------------------------- ### Configure Mokkery to Ignore Final and Inline Members Source: https://mokkery.dev/docs/Guides/Mocking This configuration allows Mokkery to ignore final or inline members within abstract or open classes, preventing compilation errors. It does not enable mocking or behavior modification for these members, only their exclusion from the mocking process. ```kotlin mokkery { ignoreInlineMembers.set(true) // ignores only inline members ignoreFinalMembers.set(true) // ignores final members (inline included) } ``` -------------------------------- ### Capture Multiple Arguments with Containers in Mokkery Source: https://mokkery.dev/docs/Guides/Matchers Demonstrates using 'Capture.container' to capture all values of a specific argument that match a given condition across multiple mock invocations. This is helpful for testing scenarios where a method is called multiple times with varying arguments. ```kotlin val container = Capture.container() // stores multiple values every { mock.getAtOrDefault(index = any(), default = any()) } returns 0 every { mock.getAtOrDefault(index = capture(container), default = 10) } returns 0 every { mock.getAtOrDefault(index = 3, default = any()) } returns 0 mock.getAtOrDefault(index = 1, default = 10) // `index` arg is captured mock.getAtOrDefault(index = 2, default = 20) // `default` parameter does not match - argument is not captured mock.getAtOrDefault(index = 3, default = 10) // answer defined later is selected here - argument is not captured println(container.values) // prints [1] ``` -------------------------------- ### Configure Mokkery Strictness Globally Source: https://mokkery.dev/docs/index Configure the default mocking and verification modes for Mokkery across your project. This is typically done in the `build.gradle.kts` file for global settings. ```kotlin mokkery { defaultMockMode.set(autoUnit) defaultVerifyMode.set(exhaustiveOrder) } ``` -------------------------------- ### Awaiting Multiple Deferreds with `all` Source: https://mokkery.dev/docs/Guides/Coroutines Demonstrates mocking a function that should await multiple `Deferred` instances and return their results as a list. The `Awaitable.all` companion object function is used for this purpose. ```kotlin import dev.mokkery.coroutines.answering.Awaitable.Companion.all val deferred1 = CompletableDeferred() val deferred2 = CompletableDeferred() val deferred3 = CompletableDeferred() everySuspend { mock.fetchAll() } awaits all(deferred1, deferred2, deferred3) ``` -------------------------------- ### Extending Answers API with Custom Answers Source: https://mokkery.dev/docs/Guides/Answers Define custom behavior for mocked function calls using the `Answer` interface and register it via the `AnsweringScope` using the `answers` function. ```APIDOC ## Extending Answers API ### Description The Answers API in Mokkery allows for the creation of custom behaviors for mocked function calls. It is built around the `Answer` interface and the `AnsweringScope`. ### Method `AnsweringScope.answers(answer: Answer)` ### Endpoint N/A (Internal library usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin // Define a custom Answer implementation private class ReturnsDelayedAnswer(private val value: T) : Answer { override fun call(scope: MokkeryBlockingCallScope): T = error("Not supported") override suspend fun call(scope: MokkerySuspendCallScope): T { delay(1_000) return value } } // Create a convenience extension for suspend functions infix fun SuspendAnsweringScope.returnsDelayed(value: T) { answers(ReturnsDelayedAnswer(value)) } // Usage: everySuspend { mock.fetchAt(any()) } returnsDelayed 10 ``` ### Response #### Success Response (200) N/A (Internal library usage) #### Response Example N/A ``` -------------------------------- ### Match Varargs with Spread Operator in Mokkery Source: https://mokkery.dev/docs/Guides/Matchers Shows how to use the spread operator (*) with matchers like 'any()' or 'containsAllInts' to match methods with a variable number of arguments (varargs). This is useful when the exact number of varargs is not fixed or when specific conditions need to be met for the varargs. ```kotlin everySuspend { mock.insertAll(1, any(), 3) } returns 0 everySuspend { mock.insertAll(1, *any(), 3) } returns 0 everySuspend { mock.insertAll(1, *containsAllInts { it != 2 }, 3) } returns 0 everySuspend { mock.insertAll(1, *matches { it.size == 2 }, 3) } returns 0 ``` -------------------------------- ### Awaiting Deferred Created on Call Source: https://mokkery.dev/docs/Guides/Coroutines Shows how to use a lambda with `awaits` to create and return a `Deferred` object dynamically on each call to the mocked function. This is useful when the deferred's behavior depends on the call arguments. ```kotlin everySuspend { mock.fetchAt(any()) } awaits { (index: Int) -> createDeferred(index) } ``` -------------------------------- ### Provide Dynamic Answer with `returnsBy` Source: https://mokkery.dev/docs/Guides/Answers Use `returnsBy` to provide an answer that is determined by a property or function reference. The value is fetched each time the mock is called. ```kotlin private var number = 1 // ... every { mock.getAt(any()) } returnsBy ::number ``` -------------------------------- ### Calling Spied Implementation with `callSpied` and `callSpiedWith` Source: https://mokkery.dev/docs/Guides/Answers When working with spies, use `callSpied()` to invoke the real implementation or `callSpiedWith(...)` to invoke it with specific arguments. ```APIDOC ## Calling Spied Implementation ### Description This feature allows you to call the real implementation of a spied method while defining additional behavior or overriding arguments. ### Method `every { ... } calls { callSpied() }` or `every { ... } calls { callSpiedWith(...) }` ### Endpoint N/A (Internal library usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin // Calling the real implementation every { spy.getAt(any()) } calls { // ... other logic callSpied() } // Calling the real implementation with overridden arguments every { spy.getAt(any()) } calls { // ... other logic callSpiedWith(3) } ``` ### Response #### Success Response (200) N/A (Internal library usage) #### Response Example N/A ``` -------------------------------- ### Apply Mokkery Gradle Plugin (Kotlin 2.3.10) Source: https://mokkery.dev/docs/index This snippet demonstrates applying the Mokkery Gradle plugin for Kotlin Multiplatform projects using Kotlin version 2.3.10. Always check for the latest compatible versions of the Kotlin and Mokkery plugins. ```kotlin plugins { kotlin("multiplatform") version "2.3.10" // ...or any other Kotlin plugin id("dev.mokkery") version "3.2.0" } ``` -------------------------------- ### Return `Result.failure` with `returnsFailure` Source: https://mokkery.dev/docs/Guides/Answers For functions returning `Result`, `returnsFailure` allows you to easily return a failed `Result` with a specified exception. ```kotlin every { mock.getAtCatching(index = 30) } returnsFailure IndexOutOfBoundsException() ``` -------------------------------- ### Repeat Sequence of Answers with `repeat` within `sequentially` Source: https://mokkery.dev/docs/Guides/Answers Inside a `sequentially` block, the `repeat` keyword allows a subset of the defined answers to be repeated after the initial sequence is exhausted. ```kotlin every { mock.getAt(any()) } sequentially { returns(0) repeat { returns(1) } } ``` -------------------------------- ### Mock Multiple Types with mockMany Source: https://mokkery.dev/docs/Guides/Mocking_multiple_types Demonstrates the basic usage of `mockMany` to create a mock for multiple types. This function accepts up to 5 types that must be supported, unique, and adhere to class/functional type restrictions. ```kotlin val mock = mockMany() ``` -------------------------------- ### Define Custom Matchers in Mokkery Source: https://mokkery.dev/docs/Guides/Matchers Illustrates how to define custom matchers in Mokkery by extending 'MokkeryMatcherScope'. This allows for creating reusable matching logic for specific argument types or patterns, such as regular expressions or checking if a value is within a set. ```kotlin // only for strings fun MokkeryMatcherScope.regex( regex: Regex ): String = matches(toString = { "regex($regex)" }, predicate = regex::matches) // for any type fun MokkeryMatcherScope.eqAnyOf( vararg values: T ): T = matches( toString = { "eqAnyOf(${values.contentToString()})" }, predicate = { values.contains(it) } ) ``` -------------------------------- ### Calling Spied Implementation in Mokkery Source: https://mokkery.dev/docs/Guides/Answers Explains how to call the real implementation of a spied object while adding extra behavior using `callSpied()` from the `calls` scope. It also covers overriding arguments with `callSpiedWith(args)`. ```kotlin every { spy.getAt(any()) } calls { // ... callSpied() } ``` ```kotlin every { spy.getAt(any()) } calls { // ... callSpiedWith(3) } ``` -------------------------------- ### Call Original Implementation with `calls original` Source: https://mokkery.dev/docs/Guides/Answers To invoke the actual implementation of the mocked method, use `calls original`. This is useful when you only want to mock certain aspects or verify behavior without completely replacing the original logic. ```kotlin every { mock.getAt(any()) } calls original ``` -------------------------------- ### Define Exception Throwing with `throws` Source: https://mokkery.dev/docs/Guides/Answers Use the `throws` keyword to configure the mock to throw a specified exception when called. This is useful for testing error handling. ```kotlin every { mock.getAt(index = any()) } throws IllegalArgumentException() ``` -------------------------------- ### Call Original Implementation with Specific Arguments using `calls originalWith` Source: https://mokkery.dev/docs/Guides/Answers The `calls originalWith` variant allows you to call the original implementation while providing specific arguments, overriding any arguments passed to the mock. ```kotlin every { mock.getAt(any()) } calls originalWith(3) ``` -------------------------------- ### Create Custom Mokkery Matchers Source: https://mokkery.dev/docs/index Define custom matchers for Mokkery to extend its matching capabilities. This includes matchers for any type based on size and matchers for strings using function references. ```kotlin // For any type! fun > MokkeryMatcherScope.hasSize(size: Int): T = matches( toString = { "hasSize($size)" }, // prettify its presence! predicate = { it.size == size } ) // By function reference! fun MokkeryMatcherScope.isNotEmpty(): String = matchesBy(String::isNotEmpty) ``` -------------------------------- ### Nest `sequentially` Blocks Source: https://mokkery.dev/docs/Guides/Answers The `sequentially` construct can be nested to create more complex sequences of answers, allowing for hierarchical control over mock responses. ```kotlin every { mock.getAt(any()) } sequentially { returns(0) sequentially { returns(1) returns(2) } returns(3) } ``` -------------------------------- ### Throw Dynamic Exception with `throwsBy` Source: https://mokkery.dev/docs/Guides/Answers Similar to `returnsBy`, `throwsBy` allows you to specify a function reference that creates and throws an exception each time the mock is invoked. ```kotlin every { mock.getAt(any()) } throwsBy ::IllegalStateException ``` -------------------------------- ### Return Specific Argument with `returnsArgAt` Source: https://mokkery.dev/docs/Guides/Answers Use `returnsArgAt` to return a specific argument that was passed to the mocked function. The argument is identified by its index. ```kotlin every { mock.getAt(index = any()) } returnsArgAt 0 ``` -------------------------------- ### Define Sequence of Answers with `sequentially` Source: https://mokkery.dev/docs/Guides/Answers The `sequentially` block enables defining a series of answers that will be returned in order for successive calls to the mock. It supports `returns`, `calls`, and `throws`. ```kotlin every { mock.getAt(any()) } sequentially { returns(0) calls { 1 } throws(IllegalStateException()) } ``` -------------------------------- ### Mocking Suspendable Functions with Core Answers Source: https://mokkery.dev/docs/Guides/Coroutines Demonstrates how to mock suspendable functions using Mokkery's core `everySuspend` and `calls` answers. This allows simulating asynchronous operations with a delay and returning a computed value. ```kotlin everySuspend { mock.fetchAt(any()) } calls { (index: Int) -> delay(1_000) index + 1 } ``` -------------------------------- ### Awaiting Channel Receive Source: https://mokkery.dev/docs/Guides/Coroutines Shows how to mock a suspendable function to await and receive an element from a `Channel`. The `Awaitable.receive` function is used, specifying the channel to receive from. ```kotlin import dev.mokkery.coroutines.answering.Awaitable.Companion.receive val channel = Channel>() everySuspend { mock.fetchAll() } awaits receive(from = channel) ``` -------------------------------- ### Legal Composite Matcher Usage with `eq` (Kotlin) Source: https://mokkery.dev/docs/Limitations Demonstrates the correct way to use composite matchers in Mokkery by explicitly using matchers like `eq` for literals, avoiding ambiguity. ```kotlin every { foo.getAt(or(eq(1), eq(2))) } returns 10 ``` -------------------------------- ### Awaiting with a Custom Delay and Lambda Source: https://mokkery.dev/docs/Guides/Coroutines Shows how to mock a suspendable function to return a value after a custom delay, with the value being determined by a lambda. The `Awaitable.delayed` function accepts `by` for delay duration and a lambda for value computation. ```kotlin import dev.mokkery.coroutines.answering.Awaitable.Companion.delayed everySuspend { mock.fetchAt(any()) } awaits delayed(by = 2.seconds) { (index: Int) -> index + 1 } ``` -------------------------------- ### Capture Varargs with Spread Operator in Mokkery Source: https://mokkery.dev/docs/Guides/Matchers Shows how to capture all arguments passed to a vararg parameter using the spread operator (*) combined with 'Capture.slot'. This allows you to inspect the entire array of varargs received by the mocked method. ```kotlin val slot = Capture.slot>() everySuspend { mock.insertAll(*capture(slot)) } returns 1 mock.insertAll(1, 2, 3) // slot contains intArrayOf(1, 2, 3) ``` -------------------------------- ### Resolving Ambiguity with superOf and superWith in Mokkery Source: https://mokkery.dev/docs/Guides/Answers Demonstrates how to resolve ambiguity when mocking multiple super types by using `superOf` to specify the supertype. It also shows how `superWith(args)` can be used to pass specific arguments to the super call. ```kotlin val mock = mockMany { every { t1.sharedFunction(any()) } calls superOf() } mock.t1.sharedFunction(2) // this calls function implementation from A with 2 ``` ```kotlin val mock = mockMany { every { t1.sharedFunction(any()) } calls superWith(3) } mock.t1.sharedFunction(2) // this calls function implementation from A with 3 ``` -------------------------------- ### Mock Shared Functions Across Types Source: https://mokkery.dev/docs/Guides/Mocking_multiple_types Illustrates how Mokkery handles shared functions with identical signatures across multiple mocked types. When a function signature is the same, it's treated as a single mockable entity, simplifying the mocking process. ```kotlin val mock = mockMany { every { t1.sharedFunction(any()) } returns "Hello world!" } // ... mock.t2.sharedFunction(1) // returns "Hello world!" ``` -------------------------------- ### Resolving Ambiguity with superOf and superWith Source: https://mokkery.dev/docs/Guides/Answers When mocking multiple types, use `superOf` or `superWith` to specify the supertype for super calls, as `original` might be ambiguous. ```APIDOC ## Resolving Ambiguity with superOf and superWith ### Description When using multiple types for mocking, the `original` keyword might not be usable due to multiple super calls. In such cases, use `superOf` or `superWith` to explicitly specify the supertype. ### Method `every { ... } calls superOf()` or `every { ... } calls superWith(...)` ### Endpoint N/A (Internal library usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin val mock = mockMany { every { t1.sharedFunction(any()) } calls superOf() } mock.t1.sharedFunction(2) // Calls implementation from A with argument 2 val mock = mockMany { every { t1.sharedFunction(any()) } calls superWith(3) } mock.t1.sharedFunction(2) // Calls implementation from A with argument 3 ``` ### Response #### Success Response (200) N/A (Internal library usage) #### Response Example N/A ``` -------------------------------- ### Register AutofillProvider for Value Classes (Kotlin) Source: https://mokkery.dev/docs/Limitations Demonstrates how to register an AutofillProvider for custom value classes when using Mokkery with WASM. This is necessary for value classes not originating from the Kotlin standard library. ```kotlin AutofillProvider.forInternals.types.register { ValueClass(null) } ```