Search code examples
iphoneioscocoacllocationocunit

CLLocationManager and unit testing


I have been trying to add some (logic) unit tests to my code recently. I've set up the tests with Kiwi, I like the BDD style and the syntax.

My problem now is that I'm trying to test some code that relies on CLLocationManager sending a correct locationManager:didUpdateToLocation:fromLocation:. However, this never happens when I run the test, presumably because CLLocationManager thinks it's not authorised. For the record, I have added a .gpx file to the test target and edited the scheme to use that file as the location (under Edit Scheme... -> Test -> Info). The same code works fine when I run the full app in the simulator. Any idea how I can get (simulated) location updates to be sent in a test case?


Solution

  • Use dependency injection to specify the location manager you'd like to use. You can either:

    • Specify it as an argument to the initializer (constructor injection)
    • Set it as a property (setter injection)

    Try to use constructor injection if you can.

    Then for real use, pass in a real CLLocationManager. But for test use, provide a fake that you can trigger to send the desired method, with preset test arguments. This also makes your test deterministic by removing any reference to your actual location.