### SwiftyMocky CLI Installation and Setup Commands Source: https://context7.com/makeawishfoundation/swiftymocky/llms.txt Install the SwiftyMocky CLI using Mint and initialize or generate mock files. Use `setup` for interactive configuration or `init` for a placeholder. ```bash # Install CLI via Mint brew install mint mint install MakeAWishFoundation/SwiftyMocky # Or via Pods (if using CocoaPods integration) # ./Pods/SwiftyMocky/bin/swiftymocky # Initialize Mockfile interactively (preferred) swiftymocky setup # Or create a blank Mockfile placeholder to fill manually swiftymocky init # Validate your configuration swiftymocky doctor # Generate Mock.generated.swift swiftymocky generate # Watch mode — regenerates on file changes (specify mock name) swiftymocky generate --watch MyMocks # Migrate from legacy .yml Sourcery configs to Mockfile swiftymocky migrate # Auto-fill testable/import entries in Mockfile swiftymocky autoimport ``` -------------------------------- ### Automatic Project Setup with SwiftyMocky CLI Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/setup-in-project.html Use this command for automatic project setup. Ensure the SwiftyMocky CLI is installed first. ```bash > swiftymocky setup # For automatic setup (preferred) ``` -------------------------------- ### Install SwiftyMocky CLI with Mint Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/installation.html Use Mint to install the SwiftyMocky CLI. This tool assists with project setup and mock generation. ```bash brew install mint ``` ```bash mint install MakeAWishFoundation/SwiftyMocky ``` -------------------------------- ### SwiftyMocky CLI Usage Examples Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/command-line-interface.html Demonstrates various ways to invoke the SwiftyMocky CLI depending on your installation method. ```bash swift run swiftymocky ``` ```bash ./Pods/SwiftyMocky/bin/swiftymocky ``` ```bash mint run MakeAWishFoundation/SwiftyMocky ``` -------------------------------- ### Setup SwiftyMocky CLI Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/overview.html Use these commands to set up or validate your SwiftyMocky configuration. Run `swiftymocky setup` if you don't have a Mockfile yet, and `swiftymocky doctor` to check your setup. ```bash swiftymocky setup ``` ```bash swiftymocky doctor ``` ```bash swiftymocky generate ``` -------------------------------- ### SwiftyMocky Setup Command Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/command-line-interface.html Use the 'setup' command to specify a project if multiple xcodeproj files are present. ```bash mocky setup .xcodeproj ``` -------------------------------- ### setup() Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/SwiftyMockyTestObserver.html Initializes the SwiftyMockyTestObserver. This method is typically called automatically by the testing framework. ```APIDOC ## setup() ### Description Initializes the SwiftyMockyTestObserver. This method is typically called automatically by the testing framework. ### Method (Implicitly called by the testing framework) ### Parameters None ``` -------------------------------- ### Install SwiftyMocky CLI with Mint Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/README.md Install the SwiftyMocky CLI using Mint. First, ensure Mint is installed via Homebrew. ```bash > brew install mint > mint install MakeAWishFoundation/SwiftyMocky ``` -------------------------------- ### Setup and Generate Mocks with SwiftyMocky CLI Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/index.html Commands to set up a Mockfile, validate your setup, and generate mocks using the SwiftyMocky CLI. ```bash swiftymocky setup ``` ```bash swiftymocky doctor ``` ```bash swiftymocky generate ``` -------------------------------- ### Install SwiftyMocky using Marathon Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/installation.html Use Marathon to install the SwiftyMocky package. Ensure Marathon is installed first. ```bash marathon install MakeAWishFoundation/SwiftyMocky ``` -------------------------------- ### Installing SwiftyMocky CLI with Mint Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/known-issues.html The recommended way to generate mocks and avoid Swift ABI version issues is by installing the SwiftyMocky CLI using Mint. ```bash swiftymocky generate ``` -------------------------------- ### Migrate Project with SwiftyMocky CLI Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/README.md Use this command to migrate an existing SwiftyMocky setup to use the new CLI tool. Ensure you have installed the CLI first. ```bash > swiftymocky migrate ``` -------------------------------- ### Automatic SwiftyMocky Setup Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/setup-in-project.html Use this command for a fully automated setup of SwiftyMocky in your project. It handles configuration and necessary file generation. ```bash swiftymocky setup ``` -------------------------------- ### Install SwiftyMocky CLI with Marathon Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/README.md Install the SwiftyMocky CLI using Marathon. This command will download and install the CLI tool. ```bash > marathon install MakeAWishFoundation/SwiftyMocky ``` -------------------------------- ### Install SwiftyMocky CLI with Mint Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/index.html Install the SwiftyMocky CLI tool using Mint, a dependency manager for Swift command-line tools. ```bash > brew install mint > mint install MakeAWishFoundation/SwiftyMocky ``` -------------------------------- ### Installing SwiftyMocky CLI with Mint Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/known-issues.html To avoid Swift ABI version conflicts with Sourcery, install the SwiftyMocky CLI using `mint`. This provides a prebuilt Sourcery version and simplifies mock generation with the command `swiftymocky generate`. ```bash swift install swifty-mocky swiftymocky generate ``` -------------------------------- ### Install SwiftyPrototype with CocoaPods Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/prototyping.html Add this line to your Podfile to include SwiftyPrototype. Then run 'pod install'. ```ruby pod "SwiftyPrototype" ``` -------------------------------- ### Setup Return Value for Instance Method Stubs Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/Global methods.html Use Given to set up the return value for instance method stubs. It prioritizes specific parameters and more recent definitions. ```swift public func Given(_ object: T, _ method: T.Given, _ policy: StubbingPolicy = .default) where T : Mock ``` -------------------------------- ### Carthage Installation Source: https://context7.com/makeawishfoundation/swiftymocky/llms.txt Add SwiftyMocky to your Cartfile for dependency management with Carthage. ```ruby # Cartfile github "MakeAWishFoundation/SwiftyMocky" ``` -------------------------------- ### Initialize SwiftyMocky Configuration Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/guides/Overview.md Run this command from your project directory after installing SwiftyMocky via CocoaPods to set up the initial Mockfile. This command is part of the CLI tool. ```zsh ./Pods/SwiftyMocky/bin/swiftymocky init ``` -------------------------------- ### Setup and Generate Mocks with CocoaPods CLI Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/README.md After integrating with CocoaPods, use these commands from your project directory to set up the Mockfile and generate mocks. ```zsh % ./Pods/SwiftyMocky/bin/swiftymocky setup % ./Pods/SwiftyMocky/bin/swiftymocky generate ``` -------------------------------- ### Manual Mockfile Initialization with SwiftyMocky CLI Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/setup-in-project.html Use this command to generate a placeholder Mockfile if you prefer manual configuration. Ensure the SwiftyMocky CLI is installed first. ```bash > swiftymocky init # Just generate placeholder for Mockfile you can fill manually ``` -------------------------------- ### Initializing ArgumentCaptor Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/ArgumentCaptor.html Initializes a new instance of ArgumentCaptor. This is the basic setup for capturing arguments. ```swift public init() ``` -------------------------------- ### Install fastlane using Homebrew Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/fastlane/README.md Alternatively, fastlane can be installed using the Homebrew package manager. ```bash brew install fastlane ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/fastlane/README.md Ensure you have the latest version of the Xcode command line tools installed before proceeding with fastlane installation. ```bash xcode-select --install ``` -------------------------------- ### Mockfile Configuration Example Source: https://context7.com/makeawishfoundation/swiftymocky/llms.txt Configure SwiftyMocky mock generation using a YAML Mockfile. Specify source directories, output paths, and import statements for generated mocks. ```yaml # Mockfile (project root) sourceryCommand: null # optional: path to custom Sourcery binary sourceryTemplate: null # optional: path to custom Sourcery template MyAppMocks: sources: include: - ./MyApp # scan these directories for AutoMockable protocols exclude: - ./MyApp/Generated # skip already-generated files output: ./MyAppTests/Mocks/Mock.generated.swift targets: - MyAppTests # used by `doctor` to validate setup testable: - MyApp # adds @testable import MyApp to generated file import: - Foundation - UIKit prototype: false # set true to use SwiftyPrototype (non-XCTest) instead # Second configuration for a separate test target MyAppIntegrationMocks: sources: include: - ./MyApp output: ./MyAppIntegrationTests/Mocks/Mock.generated.swift targets: - MyAppIntegrationTests testable: - MyApp ``` -------------------------------- ### Install SwiftyMocky CLI with Marathon Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/index.html Install the SwiftyMocky CLI tool using Marathon, another dependency manager for Swift command-line tools. ```bash > marathon install MakeAWishFoundation/SwiftyMocky ``` -------------------------------- ### Use SwiftyMocky CLI with CocoaPods Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/index.html Commands to initialize the Mockfile and generate mocks using the SwiftyMocky CLI when installed via CocoaPods. ```bash # To setup initial Mockfile % ./Pods/SwiftyMocky/bin/swiftymocky init # To generate mocks % ./Pods/SwiftyMocky/bin/swiftymocky generate ``` -------------------------------- ### Install SwiftyPrototype with Carthage Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/prototyping.html Add this line to your Cartfile to include SwiftyMocky. Then run 'carthage update' and add SwiftyPrototype to your target. ```ruby github "MakeAWishFoundation/SwiftyMocky" ``` -------------------------------- ### getProduct(policy:) Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/StubbedMethod.html Get next product, with respect to self.policy and inherited policy. ```APIDOC ## getProduct(policy:) ### Description Get next product, with respect to self.policy and inherited policy. ### Declaration ```swift public func getProduct(policy: StubbingPolicy) -> StubProduct ``` ### Parameters - `_policy_` (StubbingPolicy) - Inherited policy ### Return Value StubProduct from products array ``` -------------------------------- ### Setup Perform Closure for Instance Method Stubs Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/Global methods.html Use Perform to set up a closure that will be executed when an instance method stub is called. It prioritizes specific parameters and more recent definitions. ```swift public func Perform(_ object: T, _ method: T.Perform) where T : Mock ``` -------------------------------- ### Setup Return Value for Static Method Stubs Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/Global methods.html Use Given to set up the return value for static method stubs on a mock type. It follows the same priority rules as instance methods. ```swift public func Given(_ type: T.Type, _ method: T.StaticGiven, _ policy: StubbingPolicy = .default) where T : StaticMock ``` -------------------------------- ### SwiftyMocky Generate Commands Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/guides/Setup in project.md Commands to validate your setup and generate mocks. Add generated files to your test target. ```bash > swiftymocky doctor # validate your setup > swiftymocky generate # generate mocks ``` -------------------------------- ### Install SwiftyMocky with Ice Package Manager Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/guides/Installation.md Use Ice to add SwiftyMocky to your project dependencies. ```bash > ice add MakeAWishFoundation/SwiftyMocky ``` -------------------------------- ### Protocol with Properties Mock Setup Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/guides/Examples.md When mocking protocols with properties, ensure all non-optional and implicitly unwrapped optional properties are initialized before use. Default values are not auto-generated for properties. ```swift //sourcery: AutoMockable protocol SimpleProtocolWithProperties { var property: String { get set } weak var weakProperty: AnyObject! { get set } var propertyGetOnly: String { get } var propertyOptional: Int? { get set } var propertyImplicit: Int! { get set } } ``` ```swift let mock = SimpleProtocolWithPropertiesMock() // We should set all initial values for non optional parameters and implicitly unwrapped optional parameters mock.property = "some property" mock.propertyGetOnly = "get only ;)" mock.propertyImplicit = 1 XCTAssertEqual(mock.property, "some property") XCTAssertEqual(mock.propertyGetOnly, "get only ;)") XCTAssertEqual(mock.propertyOptional, nil) XCTAssertEqual(mock.propertyImplicit, 1) mock.propertyOptional = 2 XCTAssertEqual(mock.propertyOptional, 2) ``` -------------------------------- ### Usage Example with SwiftyPrototype Source: https://context7.com/makeawishfoundation/swiftymocky/llms.txt Usage is identical to SwiftyMocky. Import SwiftyPrototype and use the Given/Verify/Perform triad for mock interactions. This is useful for injecting mocks into your app UI for rapid prototyping. ```swift // Usage is identical to SwiftyMocky — just import SwiftyPrototype import SwiftyPrototype let mockService = PaymentServiceMock() Given(mockService, .processPayment(amount: .any, willReturn: .success)) // Inject into app UI for rapid UI prototyping without a real backend let viewModel = CheckoutViewModel(paymentService: mockService) ``` -------------------------------- ### Validate and Generate Mocks with SwiftyMocky CLI Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/setup-in-project.html Use these commands to validate your SwiftyMocky setup and generate mock files. Ensure generated files are added to your test target. ```bash swiftymocky doctor ``` ```bash swiftymocky generate ``` -------------------------------- ### Helper Script to Get Sourcery Binary Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/legacy.html A shell script to download and set up a specific version of the Sourcery binary, compatible with SwiftyMocky. It allows specifying the Swift version and output directory. ```bash [[ $# > 0 ]] && VERSION="$1" || VERSION="5.0" [[ $# > 1 ]] && OUTPUT="$2" || OUTPUT="./Pods/Sourcery/bin" SOURCERY_VERSION="0.16.0" # The version of Sourcery that is associated with this SwiftyMocky version echo "CLONE SOURCERY $SOURCERY_VERSION FOR Swift $VERSION INTO $OUTPUT" rm -r -f "$OUTPUT" ``` -------------------------------- ### Integrating SwiftyMocky with Existing Sourcery Templates Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/legacy.html Extend an existing `sourcery.yml` configuration to include SwiftyMocky templates alongside custom ones. This allows for unified mock generation within a Sourcery setup. ```yaml sources: - ./ExampleApp - ./ExampleAppTests templates: - # Path to already written Sourcery templates - ./Pods/SwiftyMocky/Sources/SwiftyMocky # <- SwiftyMocky templates output: ./ExampleApp args: testable: - ExampleApp import: - RxSwift - RxBlocking excludedSwiftLintRules: - force_cast - function_body_length - line_length - vertical_whitespace ``` -------------------------------- ### Mocking Protocols with Tuple Parameters Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/examples.html This example shows how to mock protocols with methods that accept tuples as parameters. For simple tuple matching, `.any` can be used without extra configuration. For specific tuple values or custom attributes, you must register a custom comparator in `Matcher.default`. ```swift //sourcery: AutoMockable protocol ProtocolWithTuples { func methodThatTakesTuple(tuple: (String,Int)) -> Int } let mock = ProtocolWithTuplesMock() // When using only .any - no matcher registering needed Given(mock, .methodThatTakesTuple(tuple: .any, willReturn: 0)) XCTAssertEqual(mock.methodThatTakesTuple(tuple: ("first",1)), 0) // When using custom attributes or tuples as .value(...) - registering comparator in Matcher is required! Matcher.default.register((String,Int).self) { (lhs, rhs) -> Bool in return lhs.0 == rhs.0 && lhs.1 == rhs.1 } Given(mock, .methodThatTakesTuple(tuple: .value(("first",1)), willReturn: 1)) Given(mock, .methodThatTakesTuple(tuple: .value(("second",2)), willReturn: 2)) XCTAssertEqual(mock.methodThatTakesTuple(tuple: ("first",1)), 1) XCTAssertEqual(mock.methodThatTakesTuple(tuple: ("second",2)), 2) XCTAssertEqual(mock.methodThatTakesTuple(tuple: ("first",0)), 0) Verify(mock, 4, .methodThatTakesTuple(tuple: .any)) Verify(mock, 2, .methodThatTakesTuple(tuple: .value(("first",1)))) ``` -------------------------------- ### Get Sourcery Binary Script Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/guides/Legacy.md Use this shell script to download a specific version of the Sourcery binary compatible with SwiftyMocky. You can specify the Swift version and output directory as arguments. The script clones a specific branch from the SwiftyMocky wiki repository. ```shell [[ $# > 0 ]] && VERSION="$1" || VERSION="5.0" [[ $# > 1 ]] && OUTPUT="$2" || OUTPUT="./Pods/Sourcery/bin" SOURCERY_VERSION="0.16.0" # The version of Sourcery that is associated with this SwiftyMocky version echo "CLONE SOURCERY $SOURCERY_VERSION FOR Swift $VERSION INTO $OUTPUT" rm -r -f "$OUTPUT" git clone -b "sourcery/$SOURCERY_VERSION-swift$VERSION" --single-branch --depth 1 https://github.com/MakeAWishFoundation/SwiftyMocky.wiki.git "$OUTPUT" ``` -------------------------------- ### init(_:) Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/StubbedMethod.html Creates a new method init with given products. ```APIDOC ## init(_:) ### Description Creates new method init with given products. ### Declaration ```swift public init(_ products: [StubProduct]) ``` ### Parameters - `_products_` (Array) - All stub return values ``` -------------------------------- ### Get Sourcery Script Usage Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/legacy.html This script is included with SwiftyMocky installations via Cocoapods. You can execute it from your project root. Specifying a version is optional; if omitted, the script defaults to the latest supported version. ```bash sh ./Pods/SwiftyMocky/get_sourcery.sh 4.2 ``` -------------------------------- ### Given(_:_:_:) Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/Global methods.html Sets up a stub for a static method with a specific return value and stubbing policy. ```APIDOC ## Given(_:_:_:) ### Description Sets up a stub for a static method with a specific return value and stubbing policy. ### Method `Given` ### Parameters - **`_`**: The static mock object. - **`_`**: The return value for the stub. - **`_`**: The stubbing policy to apply. ### Code Example ```swift Given(MyStaticMock.self, returns: "hello", when: .staticMethod(param:)) ``` ``` -------------------------------- ### Generate Mocks with SwiftyMocky CLI Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/README.md Use these commands to set up the Mockfile, validate your configuration, and generate mocks from your project root. Ensure the path to swiftymocky is correct. ```bash > path/to/swiftymocky setup > path/to/swiftymocky doctor > path/to/swiftymocky generate ``` -------------------------------- ### Install fastlane using RubyGems Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/fastlane/README.md Install fastlane using the RubyGems package manager. You can optionally use sudo if needed. ```bash [sudo] gem install fastlane -NV ``` -------------------------------- ### Manual SwiftyMocky Initialization Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/setup-in-project.html This command generates a placeholder Mockfile, allowing you to manually configure SwiftyMocky's behavior and settings. ```bash swiftymocky init ``` -------------------------------- ### Build SwiftyMocky CLI from Source Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/installation.html Clone the SwiftyMockyCLI repository and run 'make' in the root directory to build the command-line interface. ```bash make ``` -------------------------------- ### Mockfile Configuration Options Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/mockfile.html Explains the various options available for configuring mock generation, such as specifying custom Sourcery commands, templates, source directories, output files, and target dependencies. ```text 1. `sourceryCommand` is by default `nil`. You can use it to select custom Sourcery version/command/binary, instead of using default one bundled with SwiftyMocky CLI via `mint`. `sourceryTemplate` is custpom template location to use instead of default one. Default template would be derived from Pods,Carthage,SPM directory. If not found, CLI would use bundled template. 2. **Distinctive name** of your mock configuration. You can define as much **configurations** as you want. Each of them represents one generated file. That allows to have a separate mocks for a separate targets (you usually need that if you have more than one test target) 1. `sources` defines what files/directories would be scanned for `AutoMockable` types. 1. `include` list of included files/directories relative to project root 2. `exclude` list of excluded files/directories relative to project root 2. `output` location and name of generated mocks file. If no name specified “Mock.generated.swift” would be used 3. `targets` list of targets names. It should match the test targets that are using generated mocks file. Used to determine if your setup is correct. 4. `testable` list of testable modules imports. By default, if you generate mocks for `YourApp`, it should contain `YourApp`. Would be placed at the top of the generated file. 5. `import` list of modules imports. Would be placed at the top of the generated file. 6. `prototype` default is `false`. Set `true` if you are going to use Carthage `SwiftyPrototype` library 7. `sourcery` list of paths to additional Sourcery configurations, if you want to execute them alongside the mock generation. ``` -------------------------------- ### Get Comparator for Type Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/Matcher.html Retrieve the registered comparator closure for a given type. ```APIDOC ## Get Comparator for Type ### Description Retrieves the comparator closure associated with a specific type `T`. The comparator is a function `(T, T) -> Bool` that determines if two values of type `T` are considered equal according to the registered logic. If no comparator is found for the type, it returns `nil`. ### Declaration ```swift public func comparator(for valueType: T.Type) -> ((T, T) -> Bool)? ``` ### Parameters - `valueType` (T.Type) - The type for which to retrieve the comparator. ### Return Value An optional comparator closure `((T, T) -> Bool)?` for the specified type, or `nil` if none is registered. ``` -------------------------------- ### Given(_:_:_:) Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/Global methods.html Sets up a stub for a given method with a specific return value and stubbing policy. ```APIDOC ## Given(_:_:_:) ### Description Sets up a stub for a given method with a specific return value and stubbing policy. ### Method `Given` ### Parameters - **`_`**: The mock object. - **`_`**: The return value for the stub. - **`_`**: The stubbing policy to apply. ### Code Example ```swift Given(myMock, returns: 123, when: .aMethod(param:)) ``` ``` -------------------------------- ### init(_:returning:) Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/Structs/Stubber.html Initializes a new instance of the Stubber class. This is used internally to populate the products array with stubbed methods and their return types. ```APIDOC ## init(_:returning:) ### Description [Internal] New instance of stubber class, used to populate products array ### Declaration Swift ```swift public init(_ method: StubbedMethod, returning: ReturnedValue.Type) ``` ### Parameters `_method_` Stubbed method `_returning_` Return ``` -------------------------------- ### Get Sequence Comparator Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/Matcher.html Retrieve the default comparator for sequence types, handling element-wise comparison. ```APIDOC ## Get Sequence Comparator ### Description Retrieves the default comparator for types conforming to `Sequence`. This comparator first checks if the sequences have the same count. Then, depending on the sequence type: - For Arrays, it compares elements one by one in order. - For other Sequences, it treats them as unordered and checks if every element in one sequence has a matching element in the other. ### Declaration ```swift public func comparator(for valueType: T.Type) -> ((T, T) -> Bool)? where T : Sequence ``` ### Parameters - `valueType` (T.Type) - The sequence type for which to retrieve the comparator. ### Return Value An optional comparator closure `((T, T) -> Bool)?` for the specified sequence type, or `nil` if none is registered. ``` -------------------------------- ### Get Equatable Comparator Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/Matcher.html Retrieve the default comparator for `Equatable` types, performing standard equality checks. ```APIDOC ## Get Equatable Comparator ### Description Retrieves the default comparator for types conforming to `Equatable`. This comparator simply uses the standard equality operator (`==`) to compare two values of the specified type. ### Declaration ```swift public func comparator(for valueType: T.Type) -> ((T, T) -> Bool)? where T : Equatable ``` ### Parameters - `valueType` (T.Type) - The `Equatable` type for which to retrieve the comparator. ### Return Value An optional comparator closure `((T, T) -> Bool)?` for the specified `Equatable` type, or `nil` if none is registered. ``` -------------------------------- ### Swift Package Manager Installation Source: https://context7.com/makeawishfoundation/swiftymocky/llms.txt Add SwiftyMocky as a dependency for your test target using Swift Package Manager. ```swift // Package.swift dependencies: [ .package(url: "https://github.com/MakeAWishFoundation/SwiftyMocky", from: "4.2.0"), ], targets: [ .testTarget( name: "MyAppTests", dependencies: ["SwiftyMocky"] ) ] ``` -------------------------------- ### SwiftyMocky Generate Command Options Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/command-line-interface.html Shows how to use the 'generate' command with optional flags to control mock generation. ```bash swiftymocky options optional-mock-name ``` ```bash --disableCache ``` ```bash --verbose, -v ``` ```bash --watch, -w ``` -------------------------------- ### Migrate SwiftyMocky Configuration Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/index.html Use this command to migrate your existing SwiftyMocky configuration to the new format. Ensure you have the latest CLI installed. ```bash swiftymocky migrate ``` -------------------------------- ### Initialize Matcher Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/Classes/Matcher.html Create new instances of the Matcher class. ```APIDOC ## Initialize Matcher ### Description Initializes a new Matcher instance. ### Declaration ```swift public init() ``` ``` ```APIDOC ## Initialize Matcher with Existing Instance ### Description Creates a new Matcher instance by copying the comparators from an existing Matcher instance. ### Declaration ```swift public init(matcher: Matcher) ``` ### Parameters - **matcher** (Matcher) - The existing Matcher instance to copy comparators from. ``` -------------------------------- ### Stubbing and Verifying Methods Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/examples.html Demonstrates how to use `Given` to stub method return values based on parameter values and `Verify` to check invocation counts. It shows how to handle default values and specific parameter matches. ```swift let mock = SimpleProtocolWithMethodsMock() Verify(mock, 0, .simpleMehtodThatReturns(param: .any)) // Should be 0 // Regardless of registrations order, first will check most explicit given values Given(mock, .simpleMehtodThatReturns(param: .value("a"), willReturn: "A")) Given(mock, .simpleMehtodThatReturns(param: .value("b"), willReturn: "B")) Given(mock, .simpleMehtodThatReturns(param: .any, willReturn: "default")) XCTAssertEqual(mock.simpleMehtodThatReturns(param: "any parameter"), "default") XCTAssertEqual(mock.simpleMehtodThatReturns(param: "a"), "A") XCTAssertEqual(mock.simpleMehtodThatReturns(param: "b"), "B") XCTAssertEqual(mock.simpleMehtodThatReturns(param: "any parameter"), "default") mock.simpleMethod() mock.simpleMethod() Verify(mock, .simpleMethod()) // Should be 1+ Verify(mock, 4, .simpleMehtodThatReturns(param: .any)) // Total method invocations count should be 4 Verify(mock, 2, .simpleMehtodThatReturns(param: .value("any parameter"))) // Should be called twice wth "any parameter" Verify(mock, 1, .simpleMehtodThatReturns(param: .value("a"))) Verify(mock, 1, .simpleMehtodThatReturns(param: .value("b"))) ``` -------------------------------- ### Retrieve Equatable Comparator Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/Matcher.html Get the default comparator for types conforming to `Equatable`. This comparator simply checks for equality between two elements. ```swift public func comparator(for valueType: T.Type) -> ((T, T) -> Bool)? where T : Equatable ``` -------------------------------- ### Mockfile Configuration Options Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/mockfile.html Explains the various options available for configuring mock generation, including source inclusion/exclusion, output paths, and target specifications. ```yaml mock2: ... ``` -------------------------------- ### Integrate SwiftyMocky with Swift Package Manager Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/README.md Add SwiftyMocky to your Package.swift dependencies to integrate it using Swift Package Manager. Ensure you have installed the CLI separately. ```swift dependencies: [ .package(url: "https://github.com/MakeAWishFoundation/SwiftyMocky", from: "4.2.0"), ] ``` -------------------------------- ### Mocking Protocols with Initializers Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/examples.html Demonstrates how to instantiate mocks for protocols that have initializer requirements. Note that properties must still be set manually. ```swift // You can use all required initializers let mock1 = ProtocolWithInitializersMock(param: 1) let mock2 = ProtocolWithInitializersMock(param: 2, other: "something") // Please hav in mind, that they are only to satisfy protocol requirements // there is no logic behind that, and so all properties has to be set manually anyway mock1.param = 1 mock1.other = "" mock2.param = 2 mock2.other = "something" ``` -------------------------------- ### Retrieve Sequence Comparator Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/Matcher.html Get the default comparator for Sequence types. This comparator handles both ordered (Arrays) and unordered (other Sequences) comparisons based on element matching. ```swift public func comparator(for valueType: T.Type) -> ((T, T) -> Bool)? where T : Sequence ``` -------------------------------- ### Retrieve Comparator for a Type Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/Matcher.html Get the registered comparator closure for a given type. Returns `nil` if no comparator is found for the type. The most recently registered comparator will be returned. ```swift public func comparator(for valueType: T.Type) -> ((T, T) -> Bool)? ``` -------------------------------- ### Setting Initial Values for Properties Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/examples.html Illustrates how to set initial values for properties of a mock object. Non-optional and implicitly unwrapped optional properties require manual initialization before use to avoid fatal errors. ```swift let mock = SimpleProtocolWithPropertiesMock() // We should set all initial values for non optional parameters and implicitly unwrapped optional parameters mock.property = "some property" mock.propertyGetOnly = "get only ;)" mock.propertyImplicit = 1 XCTAssertEqual(mock.property, "some property") XCTAssertEqual(mock.propertyGetOnly, "get only ;)") XCTAssertEqual(mock.propertyOptional, nil) XCTAssertEqual(mock.propertyImplicit, 1) mock.propertyOptional = 2 XCTAssertEqual(mock.propertyOptional, 2) ``` -------------------------------- ### Mocking a Simple Protocol with Properties Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/examples.html Demonstrates how to mock a protocol that includes properties. Ensure your protocol is defined before generating mocks. ```swift protocol SomeProtocol { var property: String { get set } func method() -> Bool } let mock = SomeProtocolMock() mock.property = "test" print(mock.property) // "test" print(mock.method()) // false (default value) ``` -------------------------------- ### ArgumentCaptor Initialization Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/Classes/ArgumentCaptor.html Initializes a new instance of ArgumentCaptor. ```APIDOC ## init() ### Description Initializes a new instance of ArgumentCaptor. ### Declaration ```swift public init() ``` ``` -------------------------------- ### Prepare Mock Shell Script Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/guides/Add XCode generate action.md Create a shell script to execute mock generation. This script invokes the `swiftymocky generate` command. Ensure the script is executable. ```bash #!/bin/sh swiftymocky generate ``` -------------------------------- ### Make mock.sh Executable Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/add-xcode-generate-action.html After creating the `mock.sh` file, make it executable by running the `chmod +x mock.sh` command in your terminal. ```shell chmod +x mock.sh ``` -------------------------------- ### Mocking Protocols with Associated Types Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/handling-generics.html This example shows how to mock protocols with associated types. The mock class will be generated as a generic class, requiring manual annotations for associated types. ```swift //sourcery: AutoMockable //sourcery: associatedtype = "T1: Sequence" //sourcery: associatedtype = "T2: Comparable, EmptyProtocol" protocol AVeryAssociatedProtocol { associatedtype T1: Sequence associatedtype T2: Comparable, EmptyProtocol func fetch(for value: T2) -> T1 } ``` -------------------------------- ### Initialize Matcher from Existing Instance Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/Matcher.html Create a new Matcher instance by copying all comparators from an existing Matcher. This is useful for creating isolated matcher configurations. ```swift public init(matcher: Matcher) ``` -------------------------------- ### Extend Sourcery Configuration for SwiftyMocky Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/guides/Legacy.md Integrate SwiftyMocky templates into an existing Sourcery setup by adding the SwiftyMocky template path to your sourcery.yml file. This allows using both custom and SwiftyMocky templates. ```yaml sources: - ./ExampleApp - ./ExampleAppTests templates: - # Path to already written Sourcery templates - ./Pods/SwiftyMocky/Sources/SwiftyMocky # <- SwiftyMocky templates output: ./ExampleApp args: testable: - ExampleApp import: - RxSwift - RxBlocking excludedSwiftLintRules: - force_cast - function_body_length - line_length - vertical_whitespace ``` -------------------------------- ### Registering a Custom Comparator for Non-Equatable Types Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/matcher-support-for-not-equatable.html Register a custom comparator for a non-Equatable type with the default Matcher instance. This allows SwiftyMocky to compare instances of this type during mock verification or setup. ```swift struct User { let id: String let name: String } // ... override func setUp() { // register all comparators for custom, non equatable attributes Matcher.default.register(User.self) { lhs,rhs -> Bool in return lhs.id == rhs.id } } ``` -------------------------------- ### Setup Perform Closure for Static Method Stubs Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/Global methods.html Use Perform to set up a closure for static method stubs on a mock type. It follows the same priority rules as instance method performs. ```swift public func Perform(_ object: T.Type, _ method: T.StaticPerform) where T : StaticMock ``` -------------------------------- ### Given(_:_:_:) - Static Mock Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/contents.html Sets up a stub for a specific method on a static mock. This is used for mocking static methods or properties. ```APIDOC ## Given(_:_:_:) - Static Mock ### Description Sets up a stub for a specific method on a static mock. This is used for mocking static methods or properties. ### Method `Given` ### Endpoint N/A (Global method) ### Parameters - `mock` (StaticMock): The static mock object. - `stubbingPolicy` (StubbingPolicy): The policy to use for stubbing (e.g., .first, .last, .all). - `matcher` (Matcher): A matcher to define the conditions under which this stub should be applied. ### Request Example ```swift // Example usage (assuming 'MyClass.self' is a StaticMock) Given(MyClass.self, .staticMethod(param: .any), willReturn: 123) ``` ### Response N/A (This is a setup method, not a request/response API. ``` -------------------------------- ### Parameter Convenience Initializer: all(_:) Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/Enums/Parameter.html Use this initializer to combine multiple Parameter constraints into a single constraint. It accepts a variadic list of Parameter constraints. ```swift static func all(_ matching: Parameter...) -> Parameter ``` -------------------------------- ### Register Type for Default Comparison Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/Classes/Matcher.html Register a type to use its default comparison behavior. This is often used for custom types that conform to `Equatable` but don't require a custom comparator. For example: `Matcher.default.register(CustomType.Type.self)`. ```swift public func register(_ valueType: T.Type.Type) ``` -------------------------------- ### Given(_:_:_:) - Instance Mock Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/contents.html Sets up a stub for a specific method on an instance mock. This allows you to define the return value or behavior when the method is called. ```APIDOC ## Given(_:_:_:) - Instance Mock ### Description Sets up a stub for a specific method on an instance mock. This allows you to define the return value or behavior when the method is called. ### Method `Given` ### Endpoint N/A (Global method) ### Parameters - `mock` (Mock): The instance mock object. - `stubbingPolicy` (StubbingPolicy): The policy to use for stubbing (e.g., .first, .last, .all). - `matcher` (Matcher): A matcher to define the conditions under which this stub should be applied. ### Request Example ```swift // Example usage (assuming 'myMock' is an instance of a Mock protocol) Given(myMock, .someMethod(param1: .any, param2: .eq("expectedValue")), willReturn: "some result") ``` ### Response N/A (This is a setup method, not a request/response API. ``` -------------------------------- ### Mocking Methods That Throw Errors Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/guides/Examples.md This example demonstrates how to mock protocols with methods that throw errors. Use `Given` to specify stubbed return values or errors to be thrown. `XCTAssertThrowsError` is used to verify that errors are thrown as expected. ```swift //sourcery: AutoMockable protocol ProtocolWithThrowingMethods { func methodThatThrows() throws func methodThatReturnsAndThrows(param: Int) throws -> Bool } ``` ```swift let mock = ProtocolWithThrowingMethodsMock() Given(mock, .methodThatReturnsAndThrows(param: .value(200), willReturn: true)) Given(mock, .methodThatReturnsAndThrows(param: .value(404), willThrow: SimpleTestError.failure)) Given(mock, .methodThatReturnsAndThrows(param: .any, willThrow: SimpleTestError.other)) XCTAssertNoThrow(try mock.methodThatReturnsAndThrows(param: 200), "Should not throw") XCTAssertThrowsError(try mock.methodThatReturnsAndThrows(param: 404)) XCTAssertThrowsError(try mock.methodThatReturnsAndThrows(param: 123)) Verify(mock, 3, .methodThatReturnsAndThrows(param: .any)) ``` -------------------------------- ### Manual Mock Generation with Sourcery Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/legacy.html Manually trigger mock generation using Sourcery with a specified configuration file. Ensure the Sourcery binary is accessible. ```bash Pods/Sourcery/bin/sourcery --config mocky.yml ``` -------------------------------- ### Verifying a Method Call with a Non-Equatable Parameter Source: https://github.com/makeawishfoundation/swiftymocky/blob/master/docs/docsets/SwiftyMocky.docset/Contents/Resources/Documents/matcher-support-for-not-equatable.html After registering a comparator, you can safely verify method calls that use instances of your custom non-Equatable type as parameters. This example shows how to verify a call to `fetchUserDetails` with a specific `User` object. ```swift func testFetchUserDetails() { //... let john = User(id: "Johny123", name: "Johny") // now we can safely verify explicit parameter Verify(mockNetwork, .fetchUserDetails(for: .value(john))) } ```