Testing at the edge of your App with a Mock Server

The aim of this post is to just present how to build a simple mock server for validating the service calls on your iOS app with unit tests. The components that contains the service calls are at the edge our app and usually are not validated mostly because it is assumed that api is working fine, but this is not always true…


The mock server will respond with a controlled response and will also help you to simulate several error status responses or even delays on answers. Android and Windows phone platforms can also take profit on it.  The server will be implemented in node.js, but do not get scared, there is no need a lot of knowledge on this technology.

The server is mocking fixer public API service, and in concrete the following rest API http://api.fixer.io/latest?base=USD

What’s node.js?

Node.js is an open-source, cross-platform Javascript runtime environment for developing a diverse variety of tools and applications. For installing on your mac just type the following commands in your terminal:

$ brew install node
$ npm install express --save

Express  is a web application framework for Node, this will facilitate our task for developing our http server. For writing code, there are many text editors (sublime2atom,…) , but I recommend Visual Studio Code (VSC) because it allows you to debug the code.

The mock server

With VSC just open localMockServer folder, go to debug and press the play button.


Open your internet browser and type http://localhost:3080/latest in the url, if mock server was started well you should have to see something like this:


Developing iOS service component

Once we have an answer from the server let start to develop the iOS service component. For doing that we will create a simple single view app, please do not forget include support for unit testing.


For network service support I will use Alamofire pod, this is what it was AFNetworking in Objective-C.

For switching between real Fixer server and our mock server I will create a new schema and inside it I will define an environment variable for controlling which baseURL hast to be returned.


baseURL attribute will be calculated in the following way:

    var baseURL:String{
            if let _ = ProcessInfo().environment["LOCAL_MOCK_SERVER"]{
                return "http://localhost:3080"
            } else{
                return "https://api.fixer.io"

Remember, from now on we will work with mock server so switch to FixerClient-MockServer schema.


The service implementation is the following:

    public func latest(base :String ,
                       parameterWithDefault: String? = nil,
                       success succeed : @escaping ((DateCurrencyRate) -> ()),
                       serverFailure serverFail : @escaping ((NSError) -> ()),
                       businessFailure businessFail : @escaping ((NSError) -> ())){
        var parameters: Parameters = ["base": "USD"]
        if let _ = ProcessInfo().environment["LOCAL_MOCK_SERVER"],
            let param:String = parameterWithDefault {
        Alamofire.request(self.baseURL + "/latest",parameters:parameters).validate(statusCode: 200..<401).responseJSON { response in
            switch response.result {
            case .success:
                if let dateCurrencyRate:DateCurrencyRate = DateCurrencyRate(dictionary: response.result.value){
            case .failure(let error):
                serverFail(error as NSError)

The second function parameter is optional and only will be used for notifying server which test scenario we want to run. At the moment there are two error test cases, one for reproduce a server error and another for reproducing a business error (json with unexpected structure basically).

Unit testing our iOS app service component

The unit test implementation for forcing business error is the following:

        // Force busines error
        var asyncExpectation = expectation(description: "Force busines error")
                success: {
                dateCurrencyRate in
            },serverFailure: { (error) in
            },businessFailure: { (error) in
        self.waitForExpectations(timeout: 3, handler: nil)

After the rest of unit tests implementation just launch the test:




With the mock server all your business layer can be validated using unit testing and will isolate your development from backend. For doing this sample project I have used cocoapods 1.1.1 and XCode 8.1. You can download the code here.



Leave a Reply

Your email address will not be published. Required fields are marked *

3 × 5 =