Mastering MVVM With Swift

Ready, Set, Test

Because we moved a fair bit of logic from the view controllers of the project to the view models, we gained an important advantage, improved testability. As I mentioned earlier in this series, unit testing view controllers is known to be difficult. View models, however, are easy to test and that is the focus of the next few episodes.

Adding a Unit Test Target

Before we can start testing the view models we created earlier in this series, we need to add a target for the unit tests. Select the project in the Project Navigator, click the plus button at the bottom, and choose iOS Unit Testing Bundle.

Adding a Target

Choosing the iOS Unit Testing Bundle Template

The defaults are just fine. Make sure Language is set to Swift and Target to be Tested is set to Cloudy.

Configuring the Target

The Cloudy project should now have two targets, Cloudy and CloudyTests.

The Cloudy project should now have two targets.

Organizing the Unit Test Target

I usually create several groups in the unit testing bundle to keep files and folders organized. I create a group named Supporting Files for the Info.plist file, a group for stubs, a group for extensions, and a group for the test cases. This is what you should end up with. I also removed the test case Xcode created for us, CloudyTests.swift. We start from scratch.

Organizing the Unit Test Target

We need to update the path to the Info.plist file in the build settings of the CloudyTests target. Choose the CloudyTests target from the list of targets, select Build Settings at the top, and search for the Info.plist File build setting in the Packaging section. Change the path from CloudyTests/Info.plist to CloudyTests/Supporting Files/Info.plist.

Updating the Build Settings

Let's run the test suite to make sure the unit test target is correctly configured. We don't have any unit tests yet, but that isn't a problem. We only verify that the unit test target is ready and properly configured.

Choose a simulator from the list of devices and run the test suite by choosing Test from Xcode's Product menu. The application is installed in the simulator and the test suite is run. No errors or warnings should be visible.

Running the Test Suite

What's Next?

In the next episode, we write unit tests for the view models of the settings view controller.

Next Episode "Testing Your First View Model"