How to validate the HTML Geolocation API using Selenium WebDriver for Java
Published: 2022-07-20 21:18:12


You've probably heard of Selenium WebDriver, the widely popular browser automation library right? Did you know that you can validate the HTML Geolocation API feature using Selenium WebDriver? If not, keep reading and you'll soon find out how!


![Figure 1: Geolocation API asking for permissions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hhphihiozogc56kowu6k.png)

<i style={{ textAlign: 'center' }}>Figure 1: Geolocation API asking for permissions</i>

## Setup

For this short tutorial we'll be using the following example Java application hosted on GitHub: [Java Selenium Examples](https://github.com/ShehanAT/java-selenium-examples)

Start by cloning the project and opening it up in Eclipse or Intellij IDEA. I'll be using Eclipse for this tutorial.

Note: If you want to follow along with a different Java application feel free to do so.

### Setting up environmental variables

If you're using Eclipse, make sure to following these steps so that the paths to your local installations of `geekodriver` and `firefox.bin` are set:

1. Navigate to the Run Configurations page via `Run` -> `Run Configurations`
2. Select the `JUnit` configuration that you plan to use in running the tests
3. Navigate to the `Environment` tab
4. Click on `Add` and enter the following key/value pairs:
   - `FIREFOX_PATH`: Your local path to your `firefox` executable file. For example it should look like the following if you're using Windows: `C:\\Program Files\\Mozilla Firefox\\firefox.exe`
   - `GEEKODRIVER_PATH`: Your local path to your `geckodriver` executable file. Here's what a Windows path should look like: `C:\\..\\geckodriver\\geckodriver.exe`
5. Click `Apply` to save changes

### Testing

Let's navigate to the `src.com.codinginformer.test.SeleniumGeolocation` class and go through its methods, starting with the `@Before` method:

```
	@Before
	public void initFirefox() {
		Properties properties = new Properties();
		System.setProperty("webdriver.gecko.driver", System.getenv("GEEKODRIVER_PATH"));
		System.setProperty("webdriver.firefox.bin", System.getenv("FIREFOX_PATH"));
		WebDriver driver = new FirefoxDriver();
	}
```

The above method establishes properties for `geckodriver`. It needs the local `geckodriver` executable file path set to the `webdriver.gecko.driver` property along with the `firefox` executable file set to wherever your local `firefox` executable file resides
Finally, we instantiate the `FirefoxDriver()` class to the `driver` variable

Next, let's cover the `checkGeolocation()` method:

```
    @Test
	public void checkGeolocation() {
		String baseUrl = "https://selenium-testing-website.herokuapp.com/geolocation";

		FirefoxProfile geoDisabled = new FirefoxProfile();
		geoDisabled.setPreference("geo.enabled", true);
		geoDisabled.setPreference("geo.provider.use_corelocation", true);
		geoDisabled.setPreference("geo.prompt.testing", true);
		geoDisabled.setPreference("geo.prompt.testing.allow", true);
		DesiredCapabilities capabilities = DesiredCapabilities.firefox();
		capabilities.setCapability(FirefoxDriver.PROFILE, geoDisabled);

		@SuppressWarnings("deprecation")
		WebDriver driver = new FirefoxDriver(capabilities);

    	driver.get(baseUrl);

		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);

		driver.findElement(By.id("get-geolocation")).click();

		driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);

		Assert.assertNotNull(driver.findElement(By.id("lat-value")).getText());
		Assert.assertNotNull(driver.findElement(By.id("long-value")).getText());
	}
```

Here is an explanation for the above test:

- `FirefoxProfile geoDisabled = new FirefoxProfile();`: The `FirefoxProfile` class is a collection of settings, customizations, add-ons and other personalization settings that can be done on the Firefox browser. For our purposes of testing the HTML Geolocation API we need to enabled the following settings:

  - `geo.enabled`
  - `geo.provider.use_corelocation`
  - `geo.prompt.testing`
  - `geo.prompt.testing.allow`

- Then we have to add the `FirefoxProfile` instance to a `DesiredCapabilities` class instance, which is a class used to set properties of browsers in order to conduct web application testing(more on `DesiredCapabilities` in [this great blog post](https://www.lambdatest.com/blog/desired-capabilities-in-selenium-testing/))
- As the `new FirefoxDriver(capabilities)` expression is now deprecated, we can add a `@SuppressWarnings("deprecation")` decorator in order to silence that warning
- `driver.get(baseUrl);`: The `get()` method is used to launch a new browser session to the URL specified. This URL is specifically picked out because it contains a Geolocation section that prompts the user with a confirmation modal for tracking the user's location
- `driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS)`: The first `implicitlyWait()` method we use is for the purposes of indicating the Selenium WebDriver to wait for 2 seconds before continuing execution. This is done in order to allow ample time for the page to load
- `driver.findElement(By.id("get-geolocation")).click();`: Here we are identifying the Geolocation button by using the `By.id()` method. Afterwards, we click the button via the method `click()`
- `Assert.assertNotNull(driver.findElement(By.id("lat-value")).getText());`: After waiting for 2 seconds, we use `By.id` to identify two `<p>` elements that contains the longitude and latitude values of the user's current location

Now just right click on the `SeleniumGeolocation.java` file and select `Run As -> JUnit Test` in order to run our test.

![Figure 2: Initial Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zqdmiux82xyfd2rbrmop.png)

<i style={{ textAlign: 'center' }}>Figure 2: Intial Page</i>

![Figure 3: Geolocation coordinates shown](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xyudd3ndkyai35qu3j1v.png)
<i style={{ textAlign: 'center' }}>Figure 3: Geolocation coordinates shown</i>


![Figure 4: Our JUnit test is passing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fy2ggivzptl5q4hz3mu4.png)

<i style={{ textAlign: 'center' }}>Figure 4: Our JUnit test is passing</i>

And with that, we're able to validate the Geolocation API using by Selenium WebDriver!

Congrats if you managed to get this functionality working. If not, leave a comment in the comments section and I'll get back to you if I find the time.

## Conclusion

Thanks for reading this blog post!

If you have any questions or concerns please feel free to post a comment in this post and I will get back to you when I find the time.

If you found this article helpful please share it and make sure to follow me on [Twitter](https://twitter.com/SeanAtukorala) and [GitHub](https://github.com/ShehanAT), connect with me on [LinkedIn](https://www.linkedin.com/in/shehan-atukorala-8631491a5/) and subscribe to my [YouTube channel](https://www.youtube.com/channel/UCtxed_NljgtAXrQMMdLvhrQ).