Book

Exploring Freelancing

Navigate freelancing as a developer; find clients, manage contracts, ensure timely payment, and learn from experiences!

My first app was a gradient matching game, Gradient Game, where you match the given target gradient using your skills and the sliders, hoping to score a perfect match.

On one fine day in 2020, I got a mail that it had an issue. Both the target and the user gradient were the same, so just by clicking the evaluate button, they got 100.

Without doing anything.

That wasn’t possible; I remember adding the random method that worked well for over a year.

Then I went back to my code and realized that while taking the screenshots for App Store, I made both of them the same and shipped without reverting it.

A blunder of a release.

Time to Test

I realized that I could not make this blunder again, and the best way to ensure this doesn’t happen again is to write unit tests.

But, what to test? How to test? Where to test? Testing word is scary.

So, I went through absolute beginner tutorials intending to write only one test that checks if the target gradient is equal to the user gradient or not.

There are negligible chances of it happening, but its probability is extremely low.

Writing my First Test

To start, I created the GradientsTests inheriting from XCTestCase. I added a variable for the RGBViewModel to it.

After overriding the setUp() method, I initialized the viewModel with the gradient required in the app.

class GradientsTests: XCTestCase {
  var viewModel: RGBViewModel!
  
  override func setUp() {
    super.setUp()
    
    viewModel = .init(targetGradient: TargetGradient(), userGradient: UserGradient())
  }
}

Then, I wrote my first test that checked that the new random target gradient isn’t equal to the user gradient:

func testTargetGradientIsNotEqualToUserGradient() {
  XCTAssertNotEqual(viewModel.targetGradient.new(), viewModel.userGradient.new())
}

And that’s it, that’s how I wrote my first test!

But, wait.

Here, I’m explicitly initializing with the given gradients. If I go back to the app, make the gradients the same, and run the test, it’ll flawlessly pass.

How to deal with that situation?

I solved it by abandoning the old way of taking screenshots manually. Instead, I used snapshot. That means another post on “UI Testing to the Rescue” for some other day.

I hope you enjoyed reading! Please let me know on Twitter!

Book

Exploring Freelancing

Navigate freelancing as a developer; find clients, manage contracts, ensure timely payment, and learn from experiences!