Simulating location in tests
Improve test reliability and coverage when working with location-based code.
Overview
Automated tests are most reliable when you control all of the inputs to the code under test. When testing code that works with location APIs, use specific values for coordinates and locations so that the outcome of the tests doesn’t depend on the physical location of the device running the tests.
Test your code with different simulated locations to improve the test coverage of your location-handling code.
Simulate a static device location
If your app uses Core Location or MapKit, the app’s behavior under test can depend on the device’s location. Configure your test plan to simulate a predetermined location so tests run with repeatable inputs. To set a simulated location in a test plan, follow these steps:
Open Xcode.
Choose Product > Test Plan > Edit Test Plan.
In the test plan editor pane, choose Configuration.
Under Localization, click Simulated Location and choose a location from the menu.
For more information on configuring test plans, see Improving code assessment by organizing tests into test plans.
Replay a previously recorded journey
Test features of your app that work with changes to the device’s location by setting the simulated location to a GPX file. Xcode uses the GPX file to replay a journey while your tests are running, updating the simulated location, elevation, and velocity of the device to replicate the recorded journey. To add a GPX file to your workspace, follow these steps:
Open Xcode.
Choose Product > Test Plan > Edit Test Plan.
In the test plan editor pane, choose Configuration.
Under Localization, click Simulated Location and choose Add GPX File to Workspace.
Navigate to your GPX file and click Add.
Xcode uses the added GPX file to simulate locations in tests. You can add multiple GPX files and choose between them using the Simulated Location setting in the test plan configuration.
Construct locations for unit tests
When testing your app’s location-handling logic, you don’t need to use CLLocationManager or get the device’s location. You can construct instances of CLLocationCoordinate2D with known values for the coordinate’s latitude and longitude in the test. Pass these instances to the code under test, and validate that your code behaves as expected for the given values.
Set a simulated location for UI automation
In your UI automation tests, update the simulated device location by setting the shared XCUIDevice location to an instance of XCUILocation.
import XCTest
import CoreLocation
final class SampleAppTests: XCTestCase {
func testExample() throws {
XCUIDevice.shared.location = XCUILocation(location: CLLocation(latitude: 37.334886, longitude: -122.008988))
// Launch your app and run the test.
}
}