Thursday, 9 August, 2018 UTC


Summary

Introduction
Unit testing helps us to have confidence that our code is behaving the way we expect it to. It helps us to identify issues before we publish our code. Quick is a testing framework and Nimble is a matching framework. They are easy to use and have the advantage that they are very descriptive of what you are testing when compared with XCTest. We’re going to look at how to get started with Quick and Nimble and write a few simple tests.
Prerequisites
  • Xcode 9.3+
  • Swift 4.1+
  • A JSON file – Example JSON
  • Some knowledge of iOS programming.
  • Cocoapods installed on your machine – Installation Guide
We’re going to be building upon the “Using MVVM in iOS” tutorial that I wrote. Use this project as your starter project. Remember when using the starter project to change the development team to your own within the general settings.
Main Content

Installation

Open terminal & move into your working directory. Initialize your pods project by:
    pod init
Open the newly created Podfile within your favourite text editor. Edit your Podfile so that the WeatherForecastTests target now looks like this:
    target 'WeatherForecastTests' do
      inherit! :search_paths
      pod 'Quick'
      pod 'Nimble'
    end
Save the file and return your terminal and your working directory. Run the command:
    pod install
This will install your new frameworks and create a pods project. It will also generate a workspace. You should now use the new workspace when working on your project. So if you’ve opened your project already close it and in open the WeatherForecast.xcworkspace instead.

Setting up your test class

Within your tests target create a new group and file by:
  1. Highlighting WeatherForcastTests.
  2. FileNewGroup.
  3. Rename the new group ModelTests.
  4. Highlight your new group.
  5. FileNewFile.
  6. Select Swift file, press Next.
  7. Name the new file CurrentWeatherSpecs.
  8. Press Create.
Within your new file replace the contents with the following:
    import Quick
    import Nimble
    @testable import WeatherForecast

    class CurrentWeatherSpecs: QuickSpec {

    }
This imports the Quick and Nimble frameworks and also imports the main target for testing.

Creating stub data

Create a new group and file by:
  1. Highlighting WeatherForcastTests.
  2. FileNewGroup.
  3. Rename the new group StubData.
  4. Highlight your new group.
  5. FileNewFile.
  6. Select Empty file, press Next.
  7. Name the new file london_weather_correct.json.
  8. Press Create.
Copy and paste in the contents of the londonWeather.json file.

Writing your first test

Within your CurrentWeatherSpecs.swift file add the following code:
    override func spec() {
      var sut: CurrentWeather!
      //1 
      describe("The 'Current Weather'") {
        //2
        context("Can be created with valid JSON") {
          //3
          afterEach {
            sut = nil
          }
          //4
          beforeEach {
            //5
            if let path = Bundle(for: type(of: self)
            ).path(forResource:"london_weather_correct",
                              ofType: "json") {
                  do {
                    let data = try Data(contentsOf: URL(fileURLWithPath: path),
                                        options: .alwaysMapped)
                    let decoder = JSONDecoder()
                    decoder.keyDecodingStrategy = .convertFromSnakeCase
                    sut = try decoder.decode(CurrentWeather.self, from: data)
                  } catch {
                    fail("Problem parsing JSON")
                  }
                }
            }
            //6
            it("can parse the correct lat") {
              //7
              expect(sut.coord.lat).to(equal(1))
            }
            it("can parse the correct date time") {
              expect(sut.dt).to(equal(0))
            }
          }
        }
    }
  1. Describe the class or structure you are testing.
  2. context – under what context is the class or structure being tested. In this example we’re supplying valid JSON. You could pass in invalid JSON and ensure it handles this correctly as well.
  3. afterEach – similar to tear down, it is run after each of the tests within this context/scope.
  4. beforeEach – similar to setup, it is run before each of the tests within this context/scope.
  5. Here we pull in the JSON file from our stub data. This is the data that we will be testing against within this context.
  6. it – here we describe what we about to test. It should be a clear statement of what we are testing and we should be able to test it with just a single expectation.
  7. expect – this is the “actual“ test, we expect sut.coord.lat to equal 1. Quick & Nimble makes that quite clear by just reading the line of code.
If you run these tests (CMD+U) they will fail. Make sure you have selected a simulator or device to run the tests on. You will receive messages such:
expected to equal , got <51.51>
You will also notice in the test navigator (in the left side panel) a useful test name with a failed test symbol next to it:
The_CurrentWeather__Can_be_created_with_valid_JSON__can_parse_the_correct_lat()
This is the reason why I like testing with Quick and Nimble, it’s extremely easy to see what you have tested and what exactly has failed. You may go ahead and fix these tests by supplying the got values from the error messages into the expect statements.

Testing your ViewController

First lets, create a new group in our tests folder called ViewControllers. Within this folder create a new Swift file called ViewControllerSpecs.swift. Finally open up your Main.storyboard select the ViewController and within the identity inspector (third from left) set the storyboard identifier to ViewController.
Replace your ViewControllerSpecs.swift code with snippet below. You will notice that a lot of this is similar to that of testing the model.
    import Quick
    import Nimble
    @testable import WeatherForecast

    class ViewControllerSpecs: QuickSpec {
        override func spec() {
            var sut: ViewController!
            describe("The 'View Controller'") {
                context("Can show the correct labels text") {
                    afterEach {
                        sut = nil
                    }
                    beforeEach {
                        // 1
                        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
                        sut = storyboard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
                        _ = sut.view
                        if let path = Bundle(for: type(of: self)
                            ).path(forResource: "london_weather_correct", ofType: "json") {
                            do {
                                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
                                let decoder = JSONDecoder()
                                decoder.keyDecodingStrategy = .convertFromSnakeCase
                                sut.searchResult = try decoder.decode(CurrentWeather.self, from: data)
                            } catch {
                                fail("Problem parsing JSON")
                            }
                        }
                    }
                    it("can show the correct text within the coord label") {
                        // 2
                        expect(sut.coordLabel.text).to(equal("Lat: 51.51, Lon: -0.13"))
                    }
                    it("can show the correct location label") {
                        expect(sut.locationLabel.text).to(equal("Location: London"))
                    }
                }
            }
        }
    }
  1. Here we load the view and view controller from the storyboard. This makes sure our UIElements are not nil.
  2. Notice how we can also compare strings within the expect statement.
If you run these tests you will notice again that they fail. You’ll notice that the label text is still returning our default Label text. This is because the labels are updated on the main thread. We can change the expectation use toEventually instead.
     expect(sut.coordLabel.text).toEventually(equal("Lat: 51.51, Lon: -0.13"))
Your tests should now pass.
Conclusion
The finished example project can be found here.
We’ve learnt how to write some simple tests for your model and view controller using Quick and Nimble. There are a lot more commands that you may found useful when working within your own project, head to the GitHub repo to learn more.
The post Using Quick and Nimble for testing in iOS appeared first on Pusher Blog.