Generate Swift mocks of Kotlin Multiplatform interfaces for iOS tests.
Annotate a Kotlin interface with @SwiftMockable. When the Kotlin build links the Apple framework, it also writes a Swift protocol that mirrors the interface, marked with swift-mockable's @Mockable. swift-mockable expands it into <Name>Mock, which you can pass wherever Kotlin expects the interface.
// commonMain
@SwiftMockable
interface UserRepository {
suspend fun fetchUser(id: Int): User
val cachedUser: User?
}// iOS tests
@Test func showsUserName() async throws {
let repository = UserRepositoryMock()
repository.fetchUserHandler = { id in User(id: id, name: "Alice") }
let viewModel = UserViewModel(repository: repository) // Kotlin code taking a UserRepository
try await viewModel.load(id: 1)
#expect(viewModel.name == "Alice")
#expect(repository.fetchUserCallArguments == [1])
}- No hand-written mocks. The mocks follow the Kotlin interfaces on every build. If one falls behind, it fails to compile instead of drifting.
- No type mapping to maintain. The mirrors are read from the Swift interface that Xcode synthesizes for the framework, so
Int→Int32, nullability, renames, andsuspend→async throwsare exactly what Swift sees. - swift-mockable's API.
<name>Handler,<name>CallCount,<name>CallArguments, settable properties, andresetMock()all work as they do for any@Mockableprotocol.
| Tool | Version |
|---|---|
| Kotlin Multiplatform | 2.4 or later |
| KSP | 2.3 or later, matching your Kotlin version |
| Gradle | 8.13 or later, run with JDK 17 or later |
| Xcode | 26 or later (provides swift-synthesize-interface) |
| swift-mockable | 3.1 or later |
Mocks are generated on macOS, where Xcode is available. On other hosts, such as a Linux CI job building the Android app, the plugin registers no generation tasks and the rest of the build is unaffected.
In the Kotlin Multiplatform module that builds the Apple framework, apply KSP and kmp-swift-mockable:
// shared/build.gradle.kts
plugins {
kotlin("multiplatform")
id("com.google.devtools.ksp") version "<KSP version for your Kotlin version>"
id("io.github.yysskk.kmp-swift-mockable") version "1.0.0"
}
kmpSwiftMockable {
// The Swift file is written here, as <FrameworkBaseName>Mocks.swift.
outputDir = file("../iosApp/iosAppTests/Generated")
}The plugin adds the annotation to commonMain and its symbol processor to every Apple target. You apply KSP yourself, so that its version always matches your Kotlin version; the build fails with a message if it is missing. The plugin is published to the Gradle Plugin Portal, and the annotation and processor to Maven Central, so gradlePluginPortal() and mavenCentral() must be among your repositories.
import io.github.yysskk.kmpswiftmockable.SwiftMockable
@SwiftMockable
interface UserRepository {
suspend fun fetchUser(id: Int): User
}The interfaces must be declared in the module that builds the framework, in any source set the Apple targets compile (commonMain, iosMain, ...).
Each time a framework links, the plugin writes <outputDir>/<FrameworkBaseName>Mocks.swift, SharedMocks.swift for a framework named Shared. Add it to your iOS test target, and add swift-mockable to the target as well:
-
Xcode project. Point
outputDirinto the test target's folder. With a synchronized folder (the default for new Xcode projects), the file is picked up automatically; otherwise add it to the target once. Add theMockableproduct ofhttps://github.com/yysskk/swift-mockableto the test target. -
Swift package. Point
outputDirinto the test target's directory, and depend on swift-mockable:.package(url: "https://github.com/yysskk/swift-mockable.git", from: "3.1.0"),
The file is regenerated by the build, so ignore it in version control:
iosApp/iosAppTests/Generated/How the framework reaches Xcode decides which build generates the file:
embedAndSignAppleFrameworkForXcode(the "Run Script" build phase from the Kotlin Multiplatform wizard): every Xcode build links the framework, and so regenerates the mocks. The Kotlin build writesoutputDirfrom inside that build phase, which Xcode's script sandbox forbids; Kotlin Multiplatform already requiresENABLE_USER_SCRIPT_SANDBOXING = NOfor this phase.- XCFramework (
assemble<Name>XCFramework, or a Swift package with abinaryTarget): building the XCFramework links every slice and regenerates the mocks. - By hand:
./gradlew :shared:generateSwiftMockslinks the debug framework for the host's simulator and generates from it.
A rebuild without interface changes leaves the file untouched, so Xcode does not recompile the tests.
kmpSwiftMockable {
outputDir = file("../iosApp/iosAppTests/Generated")
condition = "DEBUG"
accessLevel = SwiftAccessLevel.PUBLIC
}| Property | Default | Description |
|---|---|---|
outputDir |
build/generated/kmp-swift-mockable |
Directory the <FrameworkBaseName>Mocks.swift file is written to. |
condition |
unset (swift-mockable's DEBUG) |
Compilation condition of the mocks, passed to @Mockable(condition:). Any condition swift-mockable accepts, such as "DEBUG || TESTING". |
accessLevel |
SwiftAccessLevel.INTERNAL |
Access level of the mirror protocols and their mocks: INTERNAL, PACKAGE, or PUBLIC. Use PUBLIC to put the mocks in a test-support module that other test targets import. |
generatorExecutable |
the generator bundled with the plugin | A kmp-swift-mockable-generator executable to run instead, such as one built from a checkout of this repository. |
SwiftAccessLevel needs import io.github.yysskk.kmpswiftmockable.gradle.SwiftAccessLevel at the top of the build script.
For each annotated interface, the generated file declares a protocol of the same name that refines the exported one and restates its requirements:
interface Closeable { fun close() }
@SwiftMockable
interface Repository { val name: String }
@SwiftMockable
interface UserRepository : Repository, Closeable {
suspend fun fetchUser(id: Int): User
fun save(user: User)
}// Generated by kmp-swift-mockable 1.0.0. Do not edit.
import Foundation
import Mockable
import Shared
/// Mirrors `Shared.Repository` for swift-mockable.
@Mockable
protocol Repository: Shared.Repository {
var name: String { get }
}
/// Mirrors `Shared.UserRepository` for swift-mockable.
@Mockable
protocol UserRepository: Shared.UserRepository, Repository {
func fetchUser(id: Int32) async throws -> Shared.User
func save(user: Shared.User)
func close()
}UserRepositoryMockconforms toShared.UserRepositorythrough the mirror, so Kotlin code accepts it.- A parent interface that is annotated as well is listed by its mirror's name, so
UserRepositoryMocksubclassesRepositoryMock. Only the first such parent is listed, because swift-mockable subclasses a single parent mock; the requirements of every other parent, annotated or not (Closeableabove), are restated. - A
suspendfunction is restated once, asasync throws. Kotlin/Native also exports it with a completion handler, but both are the same Objective-C method, so the mock'sasyncmethod serves calls from Kotlin too. - Types keep their module (
Shared.User), so they name the Kotlin types even where a mirror of the same name is in scope. Only theSwift.qualifier is dropped.
In test code, UserRepository refers to the mirror and Shared.UserRepository to the Kotlin interface.
- One module. Annotated interfaces must be declared in the module that builds the framework. Interfaces from other modules exported through it are not mirrored yet.
- Objective-C export only. Kotlin's Swift export and SKIE change how interfaces look from Swift, and are not supported yet.
- What Objective-C can express. The mirrors restate what Swift sees: generic interfaces lose their type parameters,
Flowand other Kotlin types appear as their exported classes, and asuspendfunction returning a primitive returns a boxedKotlinInt,KotlinBoolean, and so on. - Renamed declarations. The processor predicts the exported name from the Kotlin name, nesting, and
@ObjCName. When Kotlin/Native renames an interface to resolve a name clash, the build warns that the name was not found, and the interface is skipped. - swift-mockable's limits apply. A requirement swift-mockable cannot mock, such as an operator, is reported by its macro when the test target compiles.
See docs/limitations.md for details and workarounds.
- Getting started: a complete setup for an Xcode app and for a Swift package.
- Configuration: every option and task.
- How it works: the build steps, and why each design choice was made.
- Limitations.
llms.txtandllms-full.txt: this documentation in plain text.
MIT. See LICENSE.