Improving testability of CLLocationManager

It is common to find difficulties with the response of methods that are not ours when we write class tests that have external dependencies. Let’s see a typical case in mobile development where we can find this problem and find out how we can improve testability of CLLocationManager.

Improving testability of CLLocationManager

We have developed an app that has a map and uses the location services of Apple’s CoreLocation to obtain the user’s location.

As we have said, the problem comes when our class uses the CoreLocation framework. When calling the requestLocation () method, of the CLLocationManager class, it tries to retrieve the user’s location and calls our delegated method that is in the class that the CLLocationManagerDelegate delegate conforms to.

Our intention is to be able to control the values generated by methods such as requestLocation () and all this communication via delegates makes the process even more difficult.

Let’s see how we can do this by doing a mock of the external interface of the CLLocationManager using protocols.

We start with our class of location services that we will call LocationService. It is a class that has the dependency with CLLocationManager and in turn also forms its protocol (CLLocationManagerDelegate) for communication between them.

Basically the class has the getCurrentLocation method that for now asks the framework for the user’s location and we show it in the delegate.

Starting from our LocationService class, the first thing we are going to do is change how our method of getCurrentLocation returns as the location. And for this we are going to declare a callback that we will use within our method to return the location.

2: We pass the value that we want to return when the requestLocation () method is executed.

3: We inject our mock into the creation of the LocationService. Recall that in the init of the LocationService we invert the dependencies making the locationManager according to our interface and not a specific class, which in this case was CLLocationManager.

In the same way if we need to control the values of the authorization of localization permits we can do it in the same way, adding the signature of the method that we want to overwrite to our interface.

If you are interested in knowing more about CLLocationManager or mobile app development in general, I highly recommend you to subscribe to our monthly newsletter by clicking here.

If you found this article about CLLocationManager interesting, you might like…