Skip to content

Instantly share code, notes, and snippets.

@jnutting
Created May 5, 2022 21:57
Show Gist options
  • Select an option

  • Save jnutting/2d177f6a7760ba4a402790c6b3b3b01b to your computer and use it in GitHub Desktop.

Select an option

Save jnutting/2d177f6a7760ba4a402790c6b3b3b01b to your computer and use it in GitHub Desktop.

Revisions

  1. jnutting created this gist May 5, 2022.
    69 changes: 69 additions & 0 deletions Given+Expectation.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    class Given<T> {
    var sut: T

    init(_ sut: T) {
    self.sut = sut
    }

    func the<U>(_ keyPath: WritableKeyPath<T, U>, is u: U) -> Given {
    sut[keyPath: keyPath] = u
    return self
    }

    func apply(_ c: (T) -> Void) -> Given {
    c(sut)
    return self
    }

    func map<U>(_ c: (T) -> U) -> Given<U> {
    return Given<U>(c(sut))
    }

    var expect: Expectation<T> {
    return Expectation(sut: sut)
    }
    }

    struct Expectation<T> {
    let sut: T

    @discardableResult
    func the<U: Equatable>(_ keyPath: KeyPath<T, U>,
    toBe value: U) -> Expectation {
    XCTAssertEqual(sut[keyPath: keyPath], value)
    return self
    }

    @discardableResult
    func the<U: Comparable>(_ keyPath: KeyPath<T, U>,
    toBeGreaterThan value: U) -> Expectation {
    XCTAssertGreaterThan(sut[keyPath: keyPath], value)
    return self
    }

    @discardableResult
    func the<U: Comparable>(_ keyPath: KeyPath<T, U>,
    toBeLessThan value: U) -> Expectation {
    XCTAssertLessThan(sut[keyPath: keyPath], value)
    return self
    }

    @discardableResult
    func the<U: Equatable>(_ keyPath: KeyPath<T, U>,
    toNotBe value: U) -> Expectation {
    XCTAssertNotEqual(sut[keyPath: keyPath], value)
    return self
    }

    @discardableResult
    func nilValueFor<U: Equatable>(_ keyPath: KeyPath<T, U?>) -> Expectation {
    XCTAssertNil(sut[keyPath: keyPath])
    return self
    }

    @discardableResult
    func nonNilValueFor<U: Equatable>(_ keyPath: KeyPath<T, U?>) -> Expectation {
    XCTAssertNotNil(sut[keyPath: keyPath])
    return self
    }
    }