{"id":13990675,"url":"https://github.com/uber/mockolo","last_synced_at":"2025-06-11T17:40:01.330Z","repository":{"id":38180787,"uuid":"161841164","full_name":"uber/mockolo","owner":"uber","description":"Efficient Mock Generator for Swift","archived":false,"fork":false,"pushed_at":"2024-10-30T00:58:07.000Z","size":894,"stargazers_count":821,"open_issues_count":16,"forks_count":87,"subscribers_count":20,"default_branch":"master","last_synced_at":"2024-10-30T02:58:32.411Z","etag":null,"topics":["commandline","efficient","fast","generates-mocks","mock","mockgen","mockgenerator","mocking","mocking-framework","mocking-library","mocking-utility","mocks","performant","protocols","scale","scaleable","subclassing","swift","swiftsyntax","xcode"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/uber.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-12-14T21:15:01.000Z","updated_at":"2024-10-30T00:59:27.000Z","dependencies_parsed_at":"2024-03-24T07:33:13.136Z","dependency_job_id":"21419ca9-53f1-4722-a8ba-262534242a77","html_url":"https://github.com/uber/mockolo","commit_stats":{"total_commits":402,"total_committers":32,"mean_commits":12.5625,"dds":0.4054726368159204,"last_synced_commit":"dd5e7e772c76bc06e607697b7e6fdd86ae1d2005"},"previous_names":[],"tags_count":36,"template":true,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uber%2Fmockolo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uber%2Fmockolo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uber%2Fmockolo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uber%2Fmockolo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/uber","download_url":"https://codeload.github.com/uber/mockolo/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227098919,"owners_count":17730669,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["commandline","efficient","fast","generates-mocks","mock","mockgen","mockgenerator","mocking","mocking-framework","mocking-library","mocking-utility","mocks","performant","protocols","scale","scaleable","subclassing","swift","swiftsyntax","xcode"],"created_at":"2024-08-09T13:03:05.538Z","updated_at":"2025-06-11T17:40:01.322Z","avatar_url":"https://github.com/uber.png","language":"Swift","readme":"# ![](Images/logo.png)\n[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/2964/badge)](https://bestpractices.coreinfrastructure.org/projects/2964)\n[![Build Status](https://github.com/uber/mockolo/actions/workflows/builds.yml/badge.svg?branch=master)](https://github.com/uber/mockolo/actions/workflows/builds.yml)\n[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\n[![FOSSA Status](https://app.fossa.com/api/projects/custom%2B4458%2Fgithub.com%2Fuber%2Fmockolo.svg?type=shield)](https://app.fossa.com/projects/custom%2B4458%2Fgithub.com%2Fuber%2Fmockolo?ref=badge_shield)\n\n# Welcome to Mockolo\n\n**Mockolo** is an efficient mock generator for Swift. Swift doesn't provide mocking support, and Mockolo provides a fast and easy way to autogenerate mock objects that can be tested in your code. One of the main objectives of Mockolo is fast performance.  Unlike other frameworks, Mockolo provides highly performant and scalable generation of mocks via a lightweight commandline tool, so it can  run as part of a linter or a build if one chooses to do so. Try Mockolo and enhance your project's test coverage in an effective, performant way.\n\n\n## Motivation\nOne of the main objectives of this project is high performance.  There aren't many 3rd party tools that perform fast on a large codebase containing, for example, over 2M LoC or over 10K protocols.  They take several hours and even with caching enabled take several minutes.  Mockolo was built to make highly performant generation of mocks possible (in the magnitude of seconds) on such large codebase. It uses a minimal set of frameworks necessary (mentioned in the Used libraries section) to keep the code lean and efficient.\n\nAnother objective is to enable flexibility in using or overriding types if needed. This allows use of some of the features that require deeper analysis such as protocols with associated types to be simpler, more straightforward, and less fragile.\n\n\n## Disclaimer\nThis project may contain unstable APIs which may not be ready for general use. Support and/or new releases may be limited.\n\n\n## System Requirements\n\n* Swift 5.10 or later\n* Xcode 15.3 or later\n* macOS 13.0 or later and Linux\n* Support is included for the Swift Package Manager\n\n\n## Build / Install\n\nOption 1: By [Mint](https://github.com/yonaskolb/Mint)\n\n```\n$ mint install uber/mockolo\n$ mint run uber/mockolo mockolo -h // see commandline input options below\n```\n\nOption 2: [Homebrew](https://brew.sh/)\n\n```\n$ brew install mockolo\n```\n\nOption 3: Use as Build Tools Plugin with [Swift Package Manager](https://swift.org/package-manager/)\n\nAdd binaryTarget and plugin definition to your `Package.swift`.\nBinary url and checksum can be found in the [releases](https://github.com/uber/mockolo/releases) page.\n\n```swift\ntargets: [\n    ...\n    .plugin(\n        name: \"RunMockolo\",\n        capability: .buildTool(),\n        dependencies: [.target(name: \"mockolo\")]\n    ),\n    .binaryTarget(\n        name: \"mockolo\",\n        url: \"...\",\n        checksum: \"...\"\n    ),\n```\n\nImplement the plugin and specify necessary directories in the arguments.\n\n- `Plugins/RunMockolo/RunMockoloPlugin.swift`\n\n```swift\nimport PackagePlugin\n\n@main struct RunMockoloPlugin: BuildToolPlugin {\n    func createBuildCommands(context: PluginContext, target: Target) async throws -\u003e [Command] {\n        let generatedSourcePath = context.pluginWorkDirectory.appending(\"GeneratedMocks.swift\")\n        let packageRoot = context.package.directory\n\n        return [\n            .prebuildCommand(\n                displayName: \"Run mockolo\",\n                executable: try context.tool(named: \"mockolo\").path,\n                arguments: [\n                    \"-s\", packageRoot.appending(\"Sources\", \"MyModule\").string,\n                    \"-d\", generatedSourcePath,\n                ],\n                outputFilesDirectory: context.pluginWorkDirectory\n            ),\n        ]\n    }\n}\n```\n\nFinally, add the plugin to the target requiring mockolo.\n\n```swift\n.target(\n    name: \"MyTarget\",\n    dependencies: [\n        ...\n    ],\n    plugins: [\n        .plugin(name: \"RunMockolo\"),\n    ]\n),\n```\n\nOption 4: Use the binary\n\n  Go to the Release tab and download/install the binary directly.\n\nOption 5: Clone and build/run\n\n```\n$ git clone https://github.com/uber/mockolo.git\n$ cd mockolo\n$ swift build -c release\n$ .build/release/mockolo -h  // see commandline input options below\n```\n\nTo call mockolo from any location, copy the executable into a directory that is part of your `PATH` environment variable.\n\n## Run\n\n`Mockolo` is a commandline executable. To run it, pass in a list of the source file directories or file paths of a build target, and the destination filepath for the mock output. To see other arguments to the commandline, run `mockolo --help`.\n\n```\n./mockolo -s myDir -d ./OutputMocks.swift -x Images Strings\n```\n\nThis parses all the source files in `myDir` directory, excluding any files ending with `Images` or `Strings` in the file name (e.g. MyImages.swift), and generates mocks to a file at `OutputMocks.swift` in the current directory.\n\nUse --help to see the complete argument options.\n\n```\n./mockolo -h  // or --help\n\nOVERVIEW: Mockolo: Swift mock generator.\n\nUSAGE: mockolo [\u003coptions\u003e] --destination \u003cdestination\u003e\n\nOPTIONS:\n  --allow-set-call-count  If set, generated *CallCount vars will be allowed to set manually.\n  --annotation \u003cannotation\u003e\n                          A custom annotation string used to indicate if a type should be mocked (default = @mockable). (default: @mockable)\n  -j, --concurrency-limit \u003cn\u003e\n                          Maximum number of threads to execute concurrently (default = number of cores on the running machine).\n  --custom-imports \u003ccustom-imports\u003e\n                          If set, custom module imports (separated by a space) will be added to the final import statement list.\n  --enable-args-history   Whether to enable args history for all functions (default = false). To enable history per function, use the 'history' keyword in the annotation argument.\n  --disable-combine-default-values\n                          Whether to disable generating Combine streams in mocks (default = false). Set this to true to control how your streams are created in your mocks.\n  --exclude-imports \u003cexclude-imports\u003e\n                          If set, listed modules (separated by a space) will be excluded from the import statements in the mock output.\n  -x, --exclude-suffixes \u003cexclude-suffixes\u003e\n                          List of filename suffix(es) without the file extensions to exclude from parsing (separated by a space).\n  --header \u003cheader\u003e       A custom header documentation to be added to the beginning of a generated mock file.\n  -l, --logging-level \u003cn\u003e The logging level to use. Default is set to 0 (info only). Set 1 for verbose, 2 for warning, and 3 for error. (default: 0)\n  --macro \u003cmacro\u003e         If set, #if [macro] / #endif will be added to the generated mock file content to guard compilation.\n  --mock-all              If set, it will mock all types (protocols and classes) with a mock annotation (default is set to false and only mocks protocols with a mock annotation).\n  --mock-filelist \u003cmock-filelist\u003e\n                          Path to a file containing a list of dependent files (separated by a new line) of modules this target depends on.\n  --mock-final            If set, generated mock classes will have the 'final' attributes (default is set to false).\n  -mocks, --mockfiles \u003cmocks\u003e\n                          List of mock files (separated by a space) from modules this target depends on. If the --mock-filelist value exists, this will be ignored.\n  -d, --destination \u003cdestination\u003e\n                          Output file path containing the generated Swift mock classes. If no value is given, the program will exit.\n  -s, --sourcedirs \u003csourcedirs\u003e\n                          Paths to the directories containing source files to generate mocks for (separated by a space). If the --filelist or --sourcefiles values exist, they will be ignored.\n  -f, --filelist \u003cfilelist\u003e\n                          Path to a file containing a list of source file paths (delimited by a new line). If the --sourcedirs value exists, this will be ignored.\n  -srcs, --sourcefiles \u003csrcs\u003e\n                          List of source files (separated by a space) to generate mocks for. If the --sourcedirs or --filelist value exists, this will be ignored.\n  -i, --testable-imports \u003ctestable-imports\u003e\n                          If set, @testable import statements will be added for each module name in this list (separated by a space).\n  --use-template-func     If set, a common template function will be called from all functions in mock classes (default is set to false).\n  -h, --help              Show help information.\n```\n\n\n## Distribution\n\nThe `install-script.sh` will build and package up the `mockolo` binary and other necessary resources in the same bundle.\n\n```sh\n$ ./install-script.sh -h  // see input options\n$ ./install-script.sh -s [source dir] -t mockolo -d [destination dir] -o [output filename].tar.gz\n```\n\nThis will create a tarball for distribution, which contains the `mockolo` executable.\n\n\n\n## How to use\n\nFor example, Foo.swift contains:\n\n```swift\n/// @mockable\npublic protocol Foo {\n    var num: Int { get set }\n    func bar(arg: Float) -\u003e String\n}\n```\n\nRunning ```./mockolo -srcs Foo.swift -d ./OutputMocks.swift ``` will output:\n\n```swift\npublic class FooMock: Foo {\n    init() {}\n    init(num: Int = 0) {\n        self.num = num\n    }\n\n    var numSetCallCount = 0\n    var underlyingNum: Int = 0\n    var num: Int {\n        get {\n            return underlyingNum\n        }\n        set {\n            underlyingNum = newValue\n            numSetCallCount += 1\n        }\n    }\n\n    var barCallCount = 0\n    var barHandler: ((Float) -\u003e String)?\n    func bar(arg: Float) -\u003e String {\n        barCallCount += 1\n        if let barHandler = barHandler {\n            return barHandler(arg)\n        }\n        return \"\"\n    }\n}\n```\n\nThe above mock can now be used in a test as follows:\n\n```swift\nfunc testMock() {\n    let mock = FooMock(num: 5)\n    XCTAssertEqual(mock.numSetCallCount, 1)\n    mock.barHandler = { arg in\n        return String(arg)\n    }\n    XCTAssertEqual(mock.barCallCount, 1)\n}\n```\n\n## Arguments\n\nA list of override arguments can be passed in (delimited by a semicolon) to the annotation to set var types, typealiases, module names, etc.\n\n\n### Module\n\n```swift\n/// @mockable(module: prefix = Bar)\npublic protocol Foo {\n    ...\n}\n```\n\nThis will generate:\n\n```swift\npublic class FooMock: Bar.Foo {\n    ...\n}\n```\n\n### Typealias\n\n```swift\n/// @mockable(typealias: T = AnyObject; U = StringProtocol)\npublic protocol Foo {\n    associatedtype T\n    associatedtype U: Collection where U.Element == T\n    associatedtype W\n    ...\n}\n```\n\nThis will generate the following mock output:\n\n```swift\npublic class FooMock: Foo {\n    typealias T = AnyObject // overridden\n    typealias U = StringProtocol // overridden\n    typealias W = Any // default placeholder type for typealias\n    ...\n}\n```\n\n\n### RxSwift\n\nFor a var type such as an RxSwift observable:\n\n```swift\n/// @mockable(rx: intStream = ReplaySubject; doubleStream = BehaviorSubject)\npublic protocol Foo {\n    var intStream: Observable\u003cInt\u003e { get }\n    var doubleStream: Observable\u003cDouble\u003e { get }\n}\n```\n\nThis will generate:\n\n```swift\npublic class FooMock: Foo {\n    var intStreamSubject = ReplaySubject\u003cInt\u003e.create(bufferSize: 1)\n    var intStream: Observable\u003cInt\u003e { /* use intStreamSubject */ }\n    var doubleStreamSubject = BehaviorSubject\u003cInt\u003e(value: 0)\n    var doubleStream: Observable\u003cInt\u003e { /* use doubleStreamSubject */ }\n}\n```\n\n### Function Argument History\n\nTo capture function arguments history:\n\n```swift\n/// @mockable(history: fooFunc = true)\npublic protocol Foo {\n    func fooFunc(val: Int)\n    func barFunc(_ val: (a: String, Float))\n    func bazFunc(val1: Int, val2: String)\n}\n```\n\nThis will generate:\n\n```swift\npublic class FooMock: Foo {\n    var fooFuncCallCount = 0\n    var fooFuncArgValues = [Int]() // arguments captor\n    var fooFuncHandler: ((Int) -\u003e ())?\n    func fooFunc(val: Int) {\n        fooFuncCallCount += 1\n        fooFuncArgValues.append(val)   // capture arguments\n\n        if fooFuncHandler = fooFuncHandler {\n            fooFuncHandler(val)\n        }\n    }\n\n    ...\n    var barFuncArgValues = [(a: String, Float)]() // tuple is also supported.\n    ...\n\n    ...\n    var bazFuncArgValues = [(Int, String)]()\n    ...\n}\n```\n\nand also, enable the arguments captor for all functions if you passed `--enable-args-history` arg to `mockolo` command.\n\u003e NOTE: The arguments captor only supports singular types (e.g. variable, tuple). The closure variable is not supported.\n\n### Combine's AnyPublisher\n\nTo generate mocks for Combine's AnyPublisher:\n\n```swift\n/// @mockable(combine: fooPublisher = PassthroughSubject; barPublisher = CurrentValueSubject)\npublic protocol Foo {\n    var fooPublisher: AnyPublisher\u003cString, Never\u003e { get }\n    var barPublisher: AnyPublisher\u003cInt, CustomError\u003e { get }\n}\n```\n\nThis will generate:\n\n```swift\npublic class FooMock: Foo {\n    public init() { }\n\n    public var fooPublisher: AnyPublisher\u003cString, Never\u003e { return self.fooPublisherSubject.eraseToAnyPublisher() }\n    public private(set) var fooPublisherSubject = PassthroughSubject\u003cString, Never\u003e()\n\n    public var barPublisher: AnyPublisher\u003cInt, CustomError\u003e { return self.barPublisherSubject.eraseToAnyPublisher() }\n    public private(set) var barPublisherSubject = CurrentValueSubject\u003cInt, CustomError\u003e(0)\n}\n```\n\nYou can also connect an AnyPublisher to a property within the protocol.\n\nFor example:\n```swift\n/// @mockable(combine: fooPublisher = @Published foo)\npublic protocol Foo {\n    var foo: String { get }\n    var fooPublisher: AnyPublisher\u003cString, Never\u003e { get }\n}\n```\n\nThis will generate:\n```swift\npublic class FooMock: Foo {\n    public init() { }\n    public init(foo: String = \"\") {\n        self.foo = foo\n    }\n\n    public private(set) var fooSetCallCount = 0\n    @Published public var foo: String = \"\" { didSet { fooSetCallCount += 1 } }\n\n    public var fooPublisher: AnyPublisher\u003cString, Never\u003e { return self.$foo.setFailureType(to: Never.self).eraseToAnyPublisher() }\n}\n```\n\n### Overrides\n\nTo override the generated mock name:\n```swift\n/// @mockable(override: name = FooMock)\npublic protocol FooProtocol { ... }\n```\n\nThis will generate:\n```swift\npublic class FooMock: FooProtocol { ... }\n```\n\n## How to contribute to Mockolo\nSee [CONTRIBUTING](CONTRIBUTING.md) for more info.\n\n\n## Report any issues\n\nIf you run into any problems, please file a git issue. Please include:\n\n* The OS version (e.g. macOS 10.14.6)\n* The Swift version installed on your machine (from `swift --version`)\n* The Xcode version\n* The specific release version of this source code (you can use `git tag` to get a list of all the release versions or `git log` to get a specific commit sha)\n* Any local changes on your machine\n\n\n\n## License\n\nMockolo is licensed under Apache License 2.0. See [LICENSE](LICENSE.txt) for more information.\n\n    Copyright (C) 2017 Uber Technologies\n\n    Licensed under the Apache License, Version 2.0 (the \"License\");\n    you may not use this file except in compliance with the License.\n    You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n","funding_links":[],"categories":["Swift"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fuber%2Fmockolo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fuber%2Fmockolo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fuber%2Fmockolo/lists"}