Skip to content

SimpleMock is a very light way to create Mocks as you need.

License

Notifications You must be signed in to change notification settings

Tavernari/SimpleMock

Repository files navigation

Simple Mock Swift 🚀

Swift Maintainability Test Coverage

Introduction

Simple Mock Swift is a lightweight and powerful mocking tool designed specifically for Swift developers. With features supporting basic operations, concurrency-safe mocking, and intuitive setup, Simple Mock Swift ensures that you have the best tools at hand for effective testing.

Motivation

While there are many mocking libraries available, crafting mocks from scratch is often a challenging task. Simple Mock Swift strives to offer a solution that's lightweight, yet comprehensive. As Uncle Bob rightly said: "Writing your own mocks means you have to design your mocking structure. And that’s never a bad idea."

Installation

Swift Package Manager

Add the dependency to your Package.swift:

dependencies: [
    .package(url: "https://github.com/Tavernari/SimpleMock", from: "0.1.0")
],
targets: [
    .target(
        name: "YourTargetName",
        dependencies: ["SimpleMock"]
    )
]

Usage

Basic Mocking (Mock)

For typical mocking scenarios, your mock object should conform to the Mock protocol. Define an Enum with cases representing the methods you intend to use. Utilize the methods provided by Mock to set up and resolve your expectations.

class ServiceMock: Service, Mock<ServiceMock.Methods> {
    enum Methods: Hashable {
        case save(_ id: String, _ value: Int)
        case load(_ id: String)
    }
    
    func save(_ id: String, _ value: Int) throws {
        return try self.resolve(method: .save(id, value))
    }
    
    func load(_ id: String) throws -> Int {
        return try self.resolve(method: .load(id))
    }
}

Concurrency-Safe Mocking (ActorMock)

For scenarios involving concurrency, your mocks should adhere to the ActorMock protocol. This ensures that your mocks can handle concurrent accesses in a safe manner.

class ActorServiceMock: Service, ActorMock {
    enum Methods: Hashable {
        case save(_ id: String, _ value: Int)
        case load(_ id: String)
    }
    
    func save(_ id: String, _ value: Int) async throws {
        return try await self.resolve(method: .save(id, value))
    }
    
    func load(_ id: String) async throws -> Int {
        return try await self.resolve(method: .load(id))
    }
}

Testing

A comprehensive suite of tests is provided to validate the behavior of the mocks. These tests cover various scenarios, from basic mock expectations to complex concurrent interactions.

Conclusion

Simple Mock Swift is dedicated to being a versatile and efficient tool for all your Swift mocking needs. Feedback, contributions, and suggestions are always welcome!

References

About

SimpleMock is a very light way to create Mocks as you need.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages