Testing in Swift with Given When Then pattern
Published in
2 min readAug 9, 2018
Spec
Using spec
testing framework like Quick is nice, which enables BDD
style.
describe("the 'Documentation' directory") {
it("has everything you need to get started") {
let sections = Directory("Documentation").sections
expect(sections).to(contain("Organized Tests with Quick Examples and Example Groups"))
expect(sections).to(contain("Installing Quick"))
} context("if it doesn't have what you're looking for") {
it("needs to be updated") {
let you = You(awesome: true)
expect{you.submittedAnIssue}.toEventually(beTruthy())
}
}
}
But in case you don’t want additional frameworks, and want to live closer to Apple SDKs as much as possible, here are few tips.
Naming
This is from the book that I really like The Art of Unit Testing. If you don’t mind the underscore, you can follow UnitOfWork_StateUnderTest_ExpectedBehavior structure
func testSum_NegativeNumberAs1stParam_ExceptionThrown()
func testSum_NegativeNumberAs2ndParam_ExceptionThrown()
func testSum_simpleValues_Calculated()
Given When Then
This is from BDD, and practised a lot in Cucumber. You can read more on martinfowler.com/bliki/GivenWhenThen.html.