Last active
August 23, 2019 17:14
-
-
Save MarcoSantarossa/1130f50415641bc270e20a7a4644e96d to your computer and use it in GitHub Desktop.
Swift jest expectations (https://jestjs.io/docs/en/expect)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import XCTest | |
@testable import SampleApp | |
final class SampleAppTests: XCTestCase { | |
func testExample() { | |
expect("myValue").not().toBeNil() | |
expect(5).toBe(5) | |
expect(5) | |
.withMessage("my test failure message") | |
.not() | |
.toBe(10) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import XCTest | |
extension XCTestCase { | |
func expect<T: Equatable>(_ value: T) -> Matcher<T> { | |
return Matcher(expectedBase: value) | |
} | |
} | |
extension XCTestCase { | |
class Matcher<T: Equatable> { | |
private let expectedBase: T | |
private var isNegated = false | |
private var message: (() -> String)? | |
init(expectedBase: T) { | |
self.expectedBase = expectedBase | |
} | |
func withMessage(_ message: @escaping @autoclosure () -> String) -> Self { | |
self.message = message | |
return self | |
} | |
func not() -> Self { | |
isNegated = true | |
return self | |
} | |
func toBe(_ otherValue: T) { | |
if isNegated { | |
XCTAssertNotEqual(expectedBase, otherValue, message?() ?? "") | |
} else { | |
XCTAssertEqual(expectedBase, otherValue, message?() ?? "") | |
} | |
} | |
func toBeNil() { | |
if isNegated { | |
XCTAssertNotNil(expectedBase, message?() ?? "") | |
} else { | |
XCTAssertNil(expectedBase, message?() ?? "") | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment