Last active
August 29, 2015 14:02
-
-
Save lukeredpath/917ce10328fb34a0b7ba to your computer and use it in GitHub Desktop.
A more generic approach to expectations
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 Cocoa | |
protocol Matcher { | |
typealias Matchable | |
func matches(object: Matchable) -> Bool | |
} | |
class EqualMatcher<T:Equatable>: Matcher { | |
typealias Matchable = T | |
// this is a workaround for non-fixed class layout issues | |
let backingVar: T[] | |
var object: T { | |
get { | |
return backingVar[0] | |
} | |
set { | |
backingVar[0] = newValue | |
} | |
} | |
init(_ object: T) { | |
self.backingVar = [object] | |
} | |
func matches(otherObject: T) -> Bool { | |
return object == otherObject | |
} | |
} | |
class GreaterThanMatcher<T: Comparable>: Matcher { | |
typealias Matchable = T | |
// this is a workaround for non-fixed class layout issues | |
let backingVar: T[] | |
var object: T { | |
get { | |
return backingVar[0] | |
} | |
set { | |
backingVar[0] = newValue | |
} | |
} | |
init(_ object: T) { | |
self.backingVar = [object] | |
} | |
func matches(otherObject: T) -> Bool { | |
return otherObject > object | |
} | |
} | |
class Expectation<T> { | |
// this is a workaround for non-fixed class layout issues | |
let backingVar: T[] | |
var object: T { | |
get { | |
return backingVar[0] | |
} | |
set { | |
backingVar[0] = newValue | |
} | |
} | |
init(_ object: T) { | |
self.backingVar = [object] | |
} | |
func to<M: Matcher where M.Matchable == T>(matcher: M) -> Bool { | |
return matcher.matches(object) | |
} | |
func notTo<M: Matcher where M.Matchable == T>(matcher: M) -> Bool { | |
return !to(matcher) | |
} | |
} | |
func expect<T>(object: T) -> Expectation<T> { | |
return Expectation(object) | |
} | |
func equal<T:Comparable>(object: T) -> EqualMatcher<T> { | |
return EqualMatcher(object) | |
} | |
func beGreaterThan<T: Comparable>(object: T) -> GreaterThanMatcher<T> { | |
return GreaterThanMatcher(object) | |
} | |
expect(123).to(equal(123)) | |
expect(123).notTo(equal(456)) | |
expect(100).to(beGreaterThan(50)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I struggled to get the proxy/operator styles working with this so if anybody can figure out that would be great! You can see the proxy implementation here:
https://gist.github.com/lukeredpath/6af2f55f65faa52de74d