What is TDD?
Test Driven Development is a development approach that involves writing your test first and then writing the simplest code that allows you to pass that test, allowing tests to guide your application code. This process is repeated as many times as it is required.
Unit testing
Unit tests should test a single unit of code - generally a method/ function and should only be concerned with the output of that unit. We can use tools such as mocks, stubs and testing frameworks to make unit testing easier.
Generally unit testing consists of four parts:
- setup - the system under test (usually a class, object, or method) is set up e.g
account = Account.new
- exercise - the system under test is executed
account.deposit(1000)
- verify - check the result against the expectation
expect(account.show_balance).to eq 1000
- teardown - reset the system under test (usually handled by the language framework)
TDD process
A common approach to TDD is the Red-Green-Refactor lifecycle:
- Red - write a failing test
- Green - write the simplest code to pass the test
- Refactor - clean up the code that was written
TDD in swift
As I'm beginning my journey with swift I am interested in gaining exposure to the XCTest framework. In order to do this I will attempt to TDD a basic FizzBuzz app. This involves starting a project in XCode.
Fizzbuzz is a programming Kata that can be used to learn TDD and is a great way to explore TDD in a new language.
Process
- Create a file for the tests
- Write the first test e.g
func testIsDivisibleByThree() {
let brain = Brain()
let result = brain.isDivisibleByThree(number: 3)
XCTAssertEqual(result, true)
}
XCode will throw some errors that you will want to resolve step-by-step.
- Import the app into your test file by placing
@testable import FizzBuzz
at the top of file underimport XCTest
- Write the simplest code to pass the tests
class Brain {
func isDivisibleByThree(number: Int) -> Bool {
return true
}
}
- Run the tests using ⌘ + U
This process is repeated for each piece of functionality with refactors when code starts becoming repetitive.
Here is a great article on Medium Getting Started with TDD in Swift that I followed in order to build FizzBuzz in Swift.
Top comments (0)