Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock CLLocationManager in Swift

Tags:

ios

swift

mocking

I was not able to override the location property of CLLocationManager. Any ideas on how to do that?

If I do:

class MockCLLocationManager: CLLocationManager {
    var location {
        get {
            return CLLocation(latitude: 0, longitude: 0)
        }
    }
}

I get an error: '@objc' getter for non-'@objc' property

Thank you.

like image 592
Rodrigo Ruiz Avatar asked Mar 18 '15 20:03

Rodrigo Ruiz


1 Answers

This might be a bit late answer but since I was also looking for the same thing here it is:

You would you use a opposite approach. First declare a protocol you will use in case of actual CLLocationManager

protocol LocationManager{
    var location:CLLocation? {get}
}

And make the CLLocationManager conform to it

extension CLLocationManager:LocationManager{}

This way you can mock the location manager in your tests like this:

class MockLocationManager:LocationManager{
         var location:CLLocation? = CLLocation(latitude: 55.213448, longitude: 20.608194)
}

But can also pass CLLocationManager instead of it in production code.

See more here: https://blog.eliperkins.me/mocks-in-swift-via-protocols/

Edit fixed broken link

like image 152
Tomáš Kohout Avatar answered Oct 05 '22 23:10

Tomáš Kohout