Skip to content

About

Generate Swift mocks of Kotlin Multiplatform interfaces for iOS tests.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

kmp-swift-mockable

Test Coverage License

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, and suspend → async throws are exactly what Swift sees.
  • swift-mockable's API. <name>Handler, <name>CallCount, <name>CallArguments, settable properties, and resetMock() all work as they do for any @Mockable protocol.

Requirements

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.

Setup

1. Apply the plugins

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.

2. Annotate interfaces

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, ...).

3. Add the generated file to the test target

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 outputDir into 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 the Mockable product of https://github.com/yysskk/swift-mockable to the test target.

  • Swift package. Point outputDir into 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/

4. Build

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 writes outputDir from inside that build phase, which Xcode's script sandbox forbids; Kotlin Multiplatform already requires ENABLE_USER_SCRIPT_SANDBOXING = NO for this phase.
  • XCFramework (assemble<Name>XCFramework, or a Swift package with a binaryTarget): building the XCFramework links every slice and regenerates the mocks.
  • By hand: ./gradlew :shared:generateSwiftMocks links 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.

Configuration

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.

What gets generated

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()
}
  • UserRepositoryMock conforms to Shared.UserRepository through the mirror, so Kotlin code accepts it.
  • A parent interface that is annotated as well is listed by its mirror's name, so UserRepositoryMock subclasses RepositoryMock. Only the first such parent is listed, because swift-mockable subclasses a single parent mock; the requirements of every other parent, annotated or not (Closeable above), are restated.
  • A suspend function is restated once, as async throws. Kotlin/Native also exports it with a completion handler, but both are the same Objective-C method, so the mock's async method 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 the Swift. qualifier is dropped.

In test code, UserRepository refers to the mirror and Shared.UserRepository to the Kotlin interface.

Limitations

  • 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, Flow and other Kotlin types appear as their exported classes, and a suspend function returning a primitive returns a boxed KotlinInt, 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.

Documentation

License

MIT. See LICENSE.

About

Generate Swift mocks of Kotlin Multiplatform interfaces for iOS tests.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages