Skip to content

Instantly share code, notes, and snippets.

@MarcoSantarossa
Last active August 23, 2019 17:14
Show Gist options
  • Save MarcoSantarossa/1130f50415641bc270e20a7a4644e96d to your computer and use it in GitHub Desktop.
Save MarcoSantarossa/1130f50415641bc270e20a7a4644e96d to your computer and use it in GitHub Desktop.
Swift jest expectations (https://jestjs.io/docs/en/expect)
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)
}
}
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