Rodrigo Ruiz
Rodrigo Ruiz

Reputation: 4355

How to mock single function in Swift?

My question is simple, how to mock a function (not a method) in Swift. i.e., a standalone function not inside of a class.

Thank you.

EDIT:

Let's say I have the following function:

func distance(c1: CLLocation, c2: CLLocation) {
    ...
}

And I want to test my class:

class MyClass {

    func selectedLocation(location: CLLocation) {
        let text = "\(distance(self.currentLocation, location)) meters"

        self.view.showText(text)
    }

}

How do I mock the distance function?

Upvotes: 2

Views: 1816

Answers (2)

Bigman
Bigman

Reputation: 1473

Do not know if I understand this correct. Swift does support global functions.

[update: This is what I do in the unit test]

    public func getNumber()->Int //add public for unit testing
    {
        return 1
    }

    class MyClass: NSObject
    {
        func calculate()
        {
            let num = getNumber()
            println(num)
        }
    }

///unit test case
    import MyModule

    extension NSObject
    {
         public fund getNumber()->Int
         {
             return 5 //mock implementation
         }
    }


    func testExample() {

        let myInstance = MyClass()
        myInstance.calculate()

    }

Upvotes: 0

Kevlar
Kevlar

Reputation: 8924

To mock the distance function, you would need to do something like this

func distance(c1: CLLocation, c2: CLLocation) -> CLLocationDistance {
  // ...
}

class MyClass {
  var calculateDistance = distance

  func selectedLocation(location: CLLocation) {
    let text = "\(calculateDistance(self.currentLocation, location)) meters"

    self.view.showText(text)
  }

}

And in your test code you would need to do this:

func testCalculateDistanceFromLocation() {
  let thing = MyClass()
  thing.calculateDistance = { c1, c2 in /* return mock distance here */ }

  // assert correct text appeared in the view
}

This way you are providing a new implementation of the distance function when in a testing environment. As far as I know you cannot completely replace the body of a top level function dynamically such that you don't need the internal class property that stores that function value.

This is kind of cumbersome though to do this for all your functions, so I say to only do this when you feel you absolutely need to substitute this extra mocked dependency. If possible, I would encourage you to test your class as a wnole unit, if it has few or no other external dependencies and treat the distance function as an implementation detail.

Upvotes: 1

Related Questions