Unit Testing With MVVM in iOS

Updated on February 15, 2020
Bagexito profile image

Keen interest in finding different solutions to a problem. Currently exploring different architectures for iOS applications.

A Quick Overview of MVVM

In my previous article "MVVM an Improvement on MVC", we have seen how MVVM separates the View State from the Controller in ViewModel. We can drive View states represented by ViewModel in isolation. Which provides us the ability to write test cases to verify different behaviors of View.

The Test Subject

In this tutorial we will be testing "Video Games" application. It's a simple app that loads and display a list of Games on home screen. Our app flow is as follows:

  1. App will start loading Games on View load.
  2. During loading, app will display a spinner on the screen.
  3. If data gets loaded successfully, we will display items in Table View.
  4. If loading ends with error, then app will display "Unable to load games. Please try again !" message.
  5. If loaded items count is 0 then app will display "No games available at the moment." message.

I have compiled a starter project so that you can practice as we proceed. Download the project from here and open the project in Starter folder to get started.

Games List View Model

Before we start writing test cases of our GamesListViewModel, lets take a look at its behaviour. You can find GamesListViewModel in the root of starter porject.

public protocol GamesListViewModelDelegate {
    
    func errorDidOccur (vm: GamesListViewModel)
    func didStartLoading (vm: GamesListViewModel)
    func itemsLoaded (vm: GamesListViewModel)
}

public class GamesListViewModel {

    /// Notifies of different flow events 
    public var delegate: GamesListViewModelDelegate?

    /// Represetns is there any error to dislay
    /// True if Yes other wise False
    public var showError: Bool { get }

    /// Error message to display on to the screen
    public var errorMessage: String { get }

    /// Number of items in the loaded games list
    public var itemsCount: Int { get }

    /// Represents either to show loading sign or not
    public var showLoading: Bool { get }

    /// This method initiates the load request to DataService
    public func loadGames()

    /// Returns the item view model to display in list
    public func getItem(at index: Int) -> GameListItemViewModel?

    /// Takes data service to perform data operations
    public init (_ dataService: DataService)
}

In GameListViewModel we are exposing all the state information, state change notifications (GameListViewModelDelegate) and actions that UI can initiate. GameListViewModel has one dependency that is DataService which allows us to load Game list.

Prepare Test Enviornment

One of the Unit Testing principle is to isolate the test subject and simulate its dependencies in order to test all the possible cases.

Our test subject GameListViewModel has one dependency i.e. DataService. In order to isolate and simulate enviornment of GameListViewModel, we have to mock DataService behaviours. Following is the mock servicer we will be using:

protocol DataService {
    func loadGames(_ completion: @escaping ([Game]?, Error?) -> Void)
}

struct MockDataService : DataService {

    var games: [Game]?
    var error: Error?
    
    func loadGames(_ completion: @escaping ([Game]?, Error?) -> Void) {
        
        DispatchQueue.main.async {
            
            guard let games = self.games else {
                completion(nil, self.error!)
                return
            }
            completion(games, nil)
        }
    }
}

The GameListViewModel notifies events through GameListViewModelDelegate and to monitor these events we will use the following:

public struct MonitorGamesListViewModelDelegate : GamesListViewModelDelegate {

    public var errorDidOccurCallback: ((_ vm: GamesListViewModel) -> Void)?
    public var didStartLoadingCallback: ((_ vm: GamesListViewModel) -> Void)?
    public var itemsLoadedCallback: ((_ vm: GamesListViewModel) -> Void)?
    
    public func errorDidOccur (vm: GamesListViewModel) {
        errorDidOccurCallback?(vm)
    }
    public func didStartLoading (vm: GamesListViewModel) {
        didStartLoadingCallback?(vm)
    }
    public func itemsLoaded (vm: GamesListViewModel) {
        itemsLoadedCallback?(vm)
    }
}

Lets Start Testing

In our first test case we will test the behaviour of GamesListViewModel if data is loaded successfully with none empty list. To do that we tell MockDataService to send games list with one item and will check the GamesListViewModel response using MonitorGamesListViewModelDelegate.

/// After successfully loading games list
/// Expected behaviour:
/// - only show loading should be true and started loading should be called
/// - items loaded should be called and items count should be correct
func testDataLoadSuccessfully() {
    
    // setting up expectations
    let startedLoadingExpectation = expectation(description: "got callback start loading")
    let itemsLoadedExpectation = expectation(description: "items loaded expectation")
    
    // simulating the enviornment
    mockDataService.error = nil
    mockDataService.games = [ Game(title: "Happy life") ]
    
    // setting up response monitors
    responseMonitor.didStartLoadingCallback = { vm in
        XCTAssert(vm.showLoading, "Loading flag should be true")
        XCTAssert(!vm.showError, "Error flag should not be true")
        startedLoadingExpectation.fulfill()
    }
    responseMonitor.errorDidOccurCallback = { _ in
        XCTAssert(false, "Invalid error callback")
    }
    responseMonitor.itemsLoadedCallback = { vm in
        XCTAssert(!vm.showLoading, "Loading flag should not be true")
        XCTAssert(!vm.showError, "Error flag should not be true")
        XCTAssert(vm.itemsCount == 1, "Invalid items loaded")
        itemsLoadedExpectation.fulfill()
    }
    
    // performing action
    vm.loadGames()
    
    // check for expectation
    wait(for: [
        startedLoadingExpectation,
        itemsLoadedExpectation
    ], timeout: 1, enforceOrder: true)
}

In this test case we are performing five steps:

  1. Defined expectations that should be fullfiled before test exit.
  2. Setting up the dependencies to send valid response with none empty games list.
  3. Setting up the response monitor that listenes to events and asserts the expected state of ViewModel.
  4. Simulating "loadGames" action on ViewModel.
  5. Waiting for expectations to be fullfiled in perticular sequence.

Now we will test what if loading data request fails with error. According to our requirement showError should be true and errorMessage should say "Unable to load games. Please try again !".

/// Loading games list ends with error
func testDataLoadedWithError() {
        
    // setting up expectation
    let startedLoadingExpectation = expectation(description: "got callback start loading.")
    let errorOccuredExpectation = expectation(description: "loading error expectation.")
    
    // simulating the enviornment
    mockDataService.error = AppDataServiceError.invalidResponse
    mockDataService.games = nil
    
    // setting up response monitors
    responseMonitor.didStartLoadingCallback = { vm in
        XCTAssert(vm.showLoading, "Loading flag should be true.")
        XCTAssert(!vm.showError, "Error flag should not be true.")
        startedLoadingExpectation.fulfill()
    }
    responseMonitor.errorDidOccurCallback = { vm in
        
        XCTAssert(!vm.showLoading, "Loading flag should not be true.")
        XCTAssert(vm.showError, "Error flag should be true.")
        XCTAssert(vm.errorMessage == "Unable to load games. Please try again !",
                    "Invalid error message.")
        XCTAssert(vm.itemsCount == 0, "Items count should be 0.")
        errorOccuredExpectation.fulfill()
    }
    responseMonitor.itemsLoadedCallback = { _ in
        
        XCTAssert(false, "Items loaded callback should not be called.")
    }
    
    // performing action
    vm.loadGames()
    
    // check for expectation
    wait(for: [
        startedLoadingExpectation,
        errorOccuredExpectation
    ], timeout: 1, enforceOrder: true)
}

Now our final case, data loaded successfully but game list is empty. Desired result in this case is, showError should be true and errorMessage should say "No games available at the moment."

/// Loaded games list is empty
func testDataLoadedWithEmptyList() {
        
    // setting up expectation
    let startedLoadingExpectation = expectation(description: "got callback start loading.")
    let errorOccuredExpectation = expectation(description: "loading error expectation.")
    
    // simulating the enviornment
    mockDataService.error = nil
    mockDataService.games = []
    
    // setting up response monitors
    responseMonitor.didStartLoadingCallback = { vm in
        XCTAssert(vm.showLoading, "Loading flag should be true.")
        XCTAssert(!vm.showError, "Error flag should not be true.")
        startedLoadingExpectation.fulfill()
    }
    responseMonitor.errorDidOccurCallback = { vm in
        
        XCTAssert(!vm.showLoading, "Loading flag should not be true.")
        XCTAssert(vm.showError, "Error flag should be true.")
        XCTAssert(vm.errorMessage == "No games available at the moment.",
                    "Invalid error message.")
        XCTAssert(vm.itemsCount == 0, "Items count should be 0.")
        errorOccuredExpectation.fulfill()
    }
    responseMonitor.itemsLoadedCallback = { _ in
        
        XCTAssert(false, "Items loaded callback should not be called.")
    }
    
    // performing action
    vm.loadGames()
    
    // check for expectation
    wait(for: [
        startedLoadingExpectation,
        errorOccuredExpectation
    ], timeout: 1, enforceOrder: true)
}

Conclusion

We have seen how MVVM makes it easy to simulate the user behaviour without dealing with the View. We have written three test cases to see how we can test different states of the View.

You can download the final project from here. Also if you have any question or suggestion drop a comment below.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)