Friday 15 February 2019

Network Stub for UI Testing (iOS)

This is a quick walkthrough of network stub libraries options for iOS app testing. All of them start a local server and allow to specify JSON response for the request path. 

Benefits of using network stubs:

  • keep the production code clean ( no response mock code )
  • mock server instance hold by each XCTestCase, so each test case decides to use mock response or access real api by itself.
  • the response can be dynamically updated during test case.

A brief comparison is as shown in the table below:





























I've picked Swifter and Embassy and had a close look. The difference is Embassy support to mock slow network which will help if you want to test if loading view shows up correctly and doesn't block the UI. Besides,  Embassy provides more advanced usages such as recording response with other tools. The integration and basic usage of them are very similar

After installation, the only change we have to make in production code is specify the local host and scheme for mock server:


    var scheme: String {
        guard ProcessInfo.processInfo.arguments.contains("MockResponse") == false else {
            return "http://"

        }



    var host: String {
        guard ProcessInfo.processInfo.arguments.contains("MockResponse") == false else {
            return "localhost:8080"
        }

And for those UITests require mock server, add the MockResponse to launchArguments in setUp()

    
override func setUp() {
        super.setUp()
        // TODO: add mock response before launch
        app.launchArguments = ["UITests""MockResponseUsingSwifter""MockResponse"]
        app.launch()

    }


Now the most important step is map your mock response data to http request path before launch. Please check the sample code and template in my Github repo:

SampleUsageCode at Github


Note: Try Carthage to install if compiling issues can not be solved via CocoaPod.

No comments:

Post a Comment