Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling request for CLLocationManager authorization in an XCTest case

I'm working on writing some unit tests for some code that uses core location. I've got a function that will do different things depending on whether or not it has authorization to access the user's location.

If I were to run the app, grant it access to the location, and then run the test it will be able to test having authorization to location, and if I were to reset the simulator then test, it's able to test the part where it doesn't have access. While this kinda works, it's a huge pain, and definitely not automated. Especially since these tests are run by a CI server, I need a better solution.

So, is there a way to set the authorizationStatus for the CLLocationManager from XCTest, or even tap on allow access on the system prompt?

like image 465
esthepiking Avatar asked Jan 13 '16 22:01

esthepiking


People also ask

How to get location Permission in swift?

Call requestWhenInUseAuthorization or requestAlwaysAuthorization to request authorization at the point where you need location services. You may request When In Use authorization as needed; there are no limits on calling requestWhenInUseAuthorization .

How do I change location permissions in Swift?

To ask for permission to use location services even when the app is not active, use the following call instead: //Swift locationManager. requestAlwaysAuthorization() //Objective-C [locationManager requestAlwaysAuthorization]; Then add the NSLocationAlwaysUsageDescription key to your Info.

How do I run XCTest?

To run your app's XCTests on Test Lab devices, build it for testing on a Generic iOS Device: From the device dropdown at the top of your Xcode workspace window, select Generic iOS Device. In the macOS menu bar, select Product > Build For > Testing.


1 Answers

Create a Facade that interacts with the CLLocationManager. Access this Facade using some form of Dependency Injection. Then your tests can inject a fake, letting you simulate the results of calling your Facade. (You probably want a separate test for each CLAuthorizationStatus value.)

like image 66
Jon Reid Avatar answered Sep 24 '22 16:09

Jon Reid