Your First iOS & SwiftUI App: An App from Scratch

Jan 11 2022 · Swift 5.5, iOS 15, Xcode 13

Part 3: Coding in Swift

23. Intro to Test-Driven Development

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 22. Intro to Unit Testing Next episode: 24. Challenge: How to Calculate the Difference
Transcript: 23. Intro to Test-Driven Development

Now that you understand the basics of Unit Testing, I want to introduce you to a way of writing apps that some developers enjoy: Test-Driven Development.

The basic idea of Test-Driven Development is rather than writing tests AFTER you write your code, you write your tests FIRST.

Obviously, at first your tests will fail, because you haven’t written the code yet. But then when you write your code, you have some nice confidence that it works exactly the way you intended it to.

One of the nice things about test-driven development is it forces you to put some thought up-front about how you want your code to work, before you write them. It’s also a great way to ensure you definitely write tests for all your code, instead of forgetting to test some bits. In some cases, it can also result in improved code quality, and increased speed of development.

Note that not every developer likes to use Test-Driven development; and even when developers do, sometimes they only use it for certain parts of their app, like only for the data models.

Basically, whether or not to use Test-Driven Development comes down to a personal choice if this is a way you like to work, or not. We’re going to try out Test-Driven development throughout the rest of the course, and that way you can understand how it works, and if it’s something you might like to incorporate into your workflow in the future.

For this particular episode, we’re going to try out Test-Driven Development to test the Game’s points method. Right now we’ve temporarily hard-coded the method to always return 999. The next item on our programming to-do list is to properly calculate the user’s score.

Again, we could jump straight into implementing the points method, but remember that TDD says you should write your tests first, THEN write the code. So let’s write a few tests that will currently fail, but should work later on once we write the code.

Let’s give this a try!

Delete test example method, and add these:

func testScorePositive() {
  var guess = game.target + 5
  var score = game.points(sliderValue: guess)
  XCTAssertEqual(score, 95)
}

func testScoreNegative() {
  var guess = game.target - 5
  var score = game.points(sliderValue: guess)
  XCTAssertEqual(score, 95)
}