Skip to content

Instantly share code, notes, and snippets.

@rbsgn
Last active October 13, 2015 18:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbsgn/f9ecb7223d9b3950de3c to your computer and use it in GitHub Desktop.
Save rbsgn/f9ecb7223d9b3950de3c to your computer and use it in GitHub Desktop.
Sweet and concise stubbing and dummying in Swift
struct Money {
let currencyCode: String
let cents: Int
}
struct Cost {
let price: Money
let fee: Money
let total: Money
}
// In a production code you would use these structs as usual:
let cost = Cost(price: Money(currencyCode: "RUB", cents: 75000),
fee: Money(currencyCode: "RUB", cents: 7500),
total: Money(currencyCode: "RUB", cents: 82500))
// But in your tests code you could make extensions that produce dummies and stubs
extension Money {
static func dummy() -> Money {
return Money(currencyCode: "RUB", cents: 0)
}
static func stub(cents cents: Int) -> Money {
return Money(currencyCode: "RUB", cents: cents)
}
}
let costForTesting = Cost(price: .stub(cents: 1), fee: .dummy(), total: .stub(cents: 1))
@gn0meavp
Copy link

Cool!

Just one comment, the last parameter must be total, not price ;)

let costForTesting = Cost(price: .stub(cents: 1), fee: .dummy(), total: .stub(cents: 1))

@rbsgn
Copy link
Author

rbsgn commented Oct 13, 2015

@gn0meavp Thanks, man. Fixed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment