Travel the World: by using the geolocation override provided by Selenium 4

01-12-2021 door Roy de Kleijn

Location-based features are always a challenge to test. Of course, you can get out in the field and visit the physical location. It can be fun :) but not ideal for testing (especially automation).

In the example below we travel to Amsterdam, Mumbai, London and finally New York.

I reload https://my-location.org to check my current geolocation.

package io.testsmith.selenium.features;

import org.openqa.selenium.By;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v96.emulation.Emulation;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.time.Duration;
import java.util.Optional;

public class EmulateGeoLocationTests extends TestBase {

private final static Number AMSTERDAM_LAT = 52.371807;
private final static Number AMSTERDAM_LNG = 4.896029;
private final static String AMSTERDAM_ADDRESS = "Damstraat, 1012 EW Amsterdam, Netherlands";

private final static Number MUMBAI_LAT = 19.075983;
private final static Number MUMBAI_LNG = 72.877655;
private final static String MUMBAI_ADDRESS = "Santa Cruz Chamber Link Road, Halav Pool, Kurla West, Mumbai, 400070, Maharashtra, India";

private final static Number NEW_YORK_LAT = 40.712776;
private final static Number NEW_YORK_LNG = -74.005974;
private final static String NEW_YORK_ADDRESS = "City Hall Park, 1 City Hall, New York, NY 10007, United States";

private final static Number LONDON_LAT = 51.507351;
private final static Number LONDON_LNG = -0.127758;
private final static String LONDON_ADDRESS = "Charing Cross, London, WC2N, England";


@Test
public void setNewLocation() {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
driver.get("https://my-location.org/");

DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Emulation.setGeolocationOverride(Optional.of(AMSTERDAM_LAT),
Optional.of(AMSTERDAM_LNG),
Optional.of(1)));
driver.navigate().refresh();
Assert.assertTrue(wait.until(ExpectedConditions.textToBe(By.id("address"), AMSTERDAM_ADDRESS)));

devTools.send(Emulation.setGeolocationOverride(Optional.of(MUMBAI_LAT),
Optional.of(MUMBAI_LNG),
Optional.of(1)));
driver.navigate().refresh();
Assert.assertTrue(wait.until(ExpectedConditions.textToBe(By.id("address"), MUMBAI_ADDRESS)));

devTools.send(Emulation.setGeolocationOverride(Optional.of(LONDON_LAT),
Optional.of(LONDON_LNG),
Optional.of(1)));
driver.navigate().refresh();
Assert.assertTrue(wait.until(ExpectedConditions.textToBe(By.id("address"), LONDON_ADDRESS)));

devTools.send(Emulation.setGeolocationOverride(Optional.of(NEW_YORK_LAT),
Optional.of(NEW_YORK_LNG),
Optional.of(1)));
driver.navigate().refresh();
Assert.assertTrue(wait.until(ExpectedConditions.textToBe(By.id("address"), NEW_YORK_ADDRESS)));
}
}


Delen: