How to Handle Internationalization in Selenium WebDriver

There are many software products that are built for a global audience. In my tenure as a developer, I have worked on multiple web (website or web app) projects that supported different languages. Though the Selenium framework was used for automation testing, using Internationalization in Selenium WebDriver posed a huge challenge.

The major challenge was to develop automated tests that could be run on all localized UIs. When performing Internationalization in Selenium WebDriver, it is essential to create an Internationalization testing checklist to ensure that the interface of the application is displayed in the language corresponding to the client locale.

Google is a classic example of a product that is available across multiple regions – shown below are screenshots of the search page in Japanese and Hebrew:

Many developers use Internationalization testing and Localization testing interchangeably but there is a massive difference between the two. In this article, we take a look at how Internationalization in Selenium WebDriver can be used for performing Selenium test automation for software products that cater to a global audience. We also look at some of the essential points that should be a part of your Internationalization testing checklist for ensuring efficiency in the Internationalization tests.

What Is Internationalization Testing?

Internationalization is the technique of designing and preparing the software product (or application) so that it is usable in different languages, regions, and locales across the globe. Internationalization is also termed i18n, where 18 is the count of the number of letters between ‘i’ and ‘n’ in the word Internationalization.

The locale is the data that identifies the region in which the customer (or consumer) uses that particular language (or it’s variant). The formatting (and parsing) of data such as dates, currencies, numbers, etc. and the translated names of countries, languages, etc. is determined by the locale.

A software product with a global audience should be designed so that it adapts to different languages and regions without many changes. Internationalization testing is the process of testing the software for international support (i.e. different locales) while ensuring that there is no breakage in the functionality or loss of data or compromise of data security (and integrity).

Internationalization Testing Checklist

When the website (or web app) is built to handle different languages, it becomes essential to test all the features against those languages. Internationalization in Selenium WebDriver can be performed using Selenium test automation against the intended locales (or languages).

Before you proceed with the test execution, you should make sure all the requirements in the Internationalization testing checklist are met. Here are some of the necessary things that should comprise your Internationalization testing checklist:

These are some of the pivotal points that should be a part of your Internationalization testing checklist. Apart from these checks, you could also add specific rules to be followed when performing Internationalization in Selenium WebDriver. To help you finalize those rules, let’s see how to handle Internationalization in Selenium WebDriver.

Internationalization in Selenium WebDriver

There are two commonly used mechanisms for requesting the language on a localized website (or app). You have the option to use a ‘country specific URL’ as done by web products like Google. The commonly used option is choosing the language based on the Accept-Language header sent by the browser.

When performing Selenium-based test automation, I came across the Locale Switcher add-on for Chrome that lets you switch browser locales for testing the localization of your website. It supports 500 locales from across the world. Internationalization in Selenium WebDriver is demonstrated using popular languages supported by the Selenium framework (i.e. Python, Java, and C#).

Internationalization in Selenium WebDriver, or Chrome and Firefox in this case, is done by setting theintl.accept_languages preference to the necessary BCP 47 tag in the profile. The profile should be set in DriverOptions so that the updated locale is reflected in the profile.

Alternatively, the addArguments option for DriverOptions can also be used for setting the necessary locale in Chrome. Apart from the difference in syntax, the fundamentals of using DriverOptions across Python, C#, and Java remains the same. I made use of Locale Switcher for determining the locale that has to be used in the implementation.

Internationalization in ChromeDriver

Let's take a look at how to understand Internationalization in Selenium WebDriver. First, I will see how we can achieve Internationalization testing in Selenium ChromeDriver.

Here is the code snippet for achieving Internationalization for Selenium Python:

Python
 




x


 
1
# Set the locale
2
chrome_locale = 'locale-of-choice'
3
chrome_options = webdriver.ChromeOptions()
4
chrome_options.add_argument("--lang={}".format(chrome_locale))
5
# End - Set the locale


Here is the code snippet for achieving Internationalization for Selenium Java

Java
 




xxxxxxxxxx
1


 
1
ChromeOptions chromeOptions = new ChromeOptions();
2
chromeOptions.addArguments("--lang= locale-of-choice");


Here is the code snippet for achieving Internationalization for Selenium C#

C#
 




xxxxxxxxxx
1


 
1
var chromeOptions = new ChromeOptions();
2
chromeOptions.AddArgument("--lang=locale-of-choice");


Internationalization in FirefoxDriver

In this section, we will implement Internationalization in Selenium FirefoxDriver.

Here is the code snippet for achieving Internationalization for Selenium Python:

Python
 




xxxxxxxxxx
1


1
# Set the locale
2
ff_locale = 'locale-of-choice'
3
ff_profile = webdriver.FirefoxProfile()
4
ff_profile.set_preference("intl.accept_languages", firefox_locale)
5
ff_profile.update_preferences()


Here is the code snippet for achieving Internationalization for Selenium Java

Java
 




xxxxxxxxxx
1


 
1
FirefoxProfile firefoxProfile = new FirefoxProfile();
2
firefoxProfile.setPreference("intl.accept_languages", "locale-of-choice");
3
firefoxOptions.setProfile(firefoxProfile);


Here is the code snippet for achieving Internationalization for Selenium C#

C#
 




xxxxxxxxxx
1


 
1
var firefoxOptions = new FirefoxOptions();
2
firefoxOptions.SetPreference("intl.accept_languages", "locale-of-choice");


Demonstrating Internationalization in Selenium WebDriver

For demonstrating Internationalization in Selenium WebDriver for Chrome and Firefox, the following test scenarios are used:

Test Combination (Browser – Chrome 80.0, Platform – Windows 10, Locale – he-IL)

  1. Set the Chrome browser locale to ‘he-IL’.

  2. Navigate to the following URL: https://manytools.org/http-html-text/browser-language/.

  3. Assert if the locale is not set properly.

Test Combination (Browser – Firefox 78.0, Platform – macOS Mojave, Locale – ja-JP)

  1. Set the Firefox browser locale to ‘ja-JP’.

  2. Navigate to the following URL: https://manytools.org/http-html-text/browser-language/.

  3. Assert if the locale is not set properly.

The test scenarios are executed on the cloud-based Selenium Grid in LambdaTest. Once you’ve created an account with the LambdaTest platform, make a note of the user-name and access-key from the profile page. The combination of user-name and access-key is used for accessing the Grid on LambdaTest. The browser capabilities for the corresponding browser and platform combination is generated using the LambdaTest capabilities generator.

WebDriver Internationalization With Selenium Python

When performing Internationalization in Selenium WebDriver, the implementation that uses Firefox and Chrome only differs in the way we set the browser locale – the rest of the implementation remains unchanged.

Python
 




xxxxxxxxxx
1
61


1
import pytest
2
from selenium import webdriver
3
import urllib3
4
import warnings
5
from selenium.webdriver.chrome.options import Options
6
from selenium.webdriver.common.keys import Keys
7
from selenium.webdriver.firefox.options import Options
8
 
9
ch_capabilities = {
10
        "build" : "[Python] Locale Testing with Chrome & Windows on LambdaTest Selenium Grid",
11
        "name" : "[Python] Locale Testing with Chrome & Windows on LambdaTest Selenium Grid",
12
        "platform" : "Windows 10",
13
        "browserName" : "Chrome",
14
        "version" : "80.0"
15
}
16
 
17
ff_capabilities = {
18
        "build" : "[Python] Locale Testing with Firefox & macOS on LambdaTest Selenium Grid",
19
        "name" : "[Python] Locale Testing with Firefox & macOS on LambdaTest Selenium Grid",
20
        "platform" : "macOS Mojave",
21
        "browserName" : "Firefox",
22
        "version" : "78.0"
23
}
24
 
25
user_name = "user-name"
26
app_key = "access-key"
27
 
28
@pytest.fixture(scope="class")
29
def driver_chrome_init(request):
30
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
31
    
32
    # Set the locale
33
    chrome_locale = 'he-IL'
34
    chrome_options = webdriver.ChromeOptions()
35
    chrome_options.add_argument("--lang={}".format(chrome_locale))
36
    # End - Set the locale
37
 
38
    remote_url = "https://" + user_name + ":" + app_key + "@hub.lambdatest.com/wd/hub"
39
    # web_driver = webdriver.Chrome()
40
    web_driver = webdriver.Remote(command_executor = remote_url, desired_capabilities = ch_capabilities, options=chrome_options)
41
    request.cls.driver = web_driver
42
    yield
43
    web_driver.close()
44
    web_driver.quit()
45
   
46
@pytest.fixture(scope="class")
47
def driver_ff_init(request):
48
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
49
    # Set the locale
50
    firefox_locale = 'ja-JP'
51
    ff_profile = webdriver.FirefoxProfile()
52
    ff_profile.set_preference("intl.accept_languages", firefox_locale)
53
    ff_profile.update_preferences()
54
    # End - Set the locale
55
 
56
    remote_url = "https://" + user_name + ":" + app_key + "@hub.lambdatest.com/wd/hub"
57
    web_driver = webdriver.Remote(command_executor = remote_url, desired_capabilities = ff_capabilities, browser_profile=ff_profile)
58
    # web_driver = webdriver.Firefox()
59
    request.cls.driver = web_driver
60
    yield
61
    web_driver.quit()


Code Walk Through

Step 1: The capabilities for the two test scenarios are generated using the LambdaTest capabilities generator. Shown below is the capabilities for Test Scenario 1:

Python
 




xxxxxxxxxx
1


1
ch_capabilities = {
2
        "build" : "[Python] Locale Testing with Chrome & Windows on LambdaTest Selenium Grid",
3
        "name" : "[Python] Locale Testing with Chrome & Windows on LambdaTest Selenium Grid",
4
        "platform" : "Windows 10",
5
        "browserName" : "Chrome",
6
        "version" : "80.0"
7
}


Step 2: The functions driver_chrome_init() and driver_ff_init() are used for the initialization and de-initialization of the Chrome and Firefox browsers, respectively. These functions are used with the @pytest.mark.usefixtures in the test code.

The scope is set to ‘class’ so that a fresh browser instance is used for every test scenario.

Python
 




xxxxxxxxxx
1


1
@pytest.fixture(scope="class")
2
def driver_chrome_init(request):
3
………………………………………………….
4
………………………………………………….
5
       
6
@pytest.fixture(scope="class")
7
def driver_ff_init(request):
8
………………………………………………….
9
………………………………………………….


Step 3: The required locale, i.e. ‘he-IL’, is set using the instance of ChromeOptions (i.e chrome_options). The browser capabilities are also set using chrome_options instead of DesiredCapabilities, since ChromeOptions offers convenient methods for setting ChromeDriver specific capabilities. This is an important step in implementing Internationalization with Selenium WebDriver.

Python
 




xxxxxxxxxx
1


 
1
chrome_locale = 'he-IL'
2
chrome_options = webdriver.ChromeOptions()


Step 4The add_argument method in ChromeOptions is used for setting the necessary locale.

Python
 




xxxxxxxxxx
1


1
chrome_options.add_argument("--lang={}".format(chrome_locale))


Step 5The combination of user-name and access-key are used for accessing the LambdaTest Grid URL .

Python
 




xxxxxxxxxx
1


1
remote_url = "https://" + user_name + ":" + app_key + "@hub.lambdatest.com/wd/hub"


Step 6The Selenium WebDriver API uses the LambdaTest Grid URL and browser capabilities (i.e. ch_capabilities) that was generated using the LambdaTest Capabilities Generator.

Python
 




xxxxxxxxxx
1


 
1
web_driver = webdriver.Remote(command_executor = remote_url, desired_capabilities = ch_capabilities, options=chrome_options)


Step 7A new Firefox Profile is created using the FirefoxProfile() method offered by the webdriver package.

Python
 




xxxxxxxxxx
1


 
1
firefox_locale = 'ja-JP'
2
ff_profile = webdriver.FirefoxProfile()


Step 8The set_preference() method in FirefoxProfile is used with intl.accept_languages set to ‘ja-JP’ (i.e. locale under test). The update_preferences() method is called to update the preferences set using the set_preference() method.

Python
 






Python
 






Code Walk Through

The implementation of Internationalization in Selenium WebDriver is self-explanatory hence, I will not go deeper into the aspects of implementation.

To verify whether the browser locale is set to the expected locale (i.e. he-IL for Test Scenario 1 and ja-JP for Test Scenario 2), the driver.execute_script() method is used for executing JavaScript within the browser window.

The JS code returns the browser language which is compared with the expected locale. assert is raised if the language does not match the expected locale.

Python
 




xxxxxxxxxx
1


1
language = self.driver.execute_script("return window.navigator.userlanguage || window.navigator.language")
2
assert language == 'he-IL'


Execution

The execution is performed by invoking the following command on the terminal:

Shell
 






Here is the screenshot of the execution which indicates the tests passed (i.e. the browser locale was set without any issues):

WebDriver Internationalization With Selenium C#

Like Python, the implementation of Internationalization in Selenium WebDriver that uses Firefox and Chrome only differs in the handling of the browser locale.

C#
 




xxxxxxxxxx
1
66


1
using System;
2
using System.Globalization;
3
using System.Reflection;
4
using System.Diagnostics;
5
using OpenQA.Selenium;
6
using OpenQA.Selenium.Remote;
7
using System.Threading;
8
using System.Collections.Generic;
9
using NUnit.Framework;
10
using OpenQA.Selenium.Chrome;
11
using FluentAssertions;
12
 
13
namespace ParallelLTSelenium
14
{
15
    [TestFixture]
16
    public class ParallelLTTests
17
    {
18
        IWebDriver driver;
19
 
20
        [Test]
21
        public void test_locale_chrome()
22
        {
23
            String username = "user-name";
24
            String accesskey = "access-key";
25
            String gridURL = "@hub.lambdatest.com/wd/hub";
26
 
27
            var chromeOptions = new ChromeOptions();
28
            chromeOptions.AddArgument("--lang=he-IL");
29
 
30
            chromeOptions.AddAdditionalCapability("user", username, true);
31
            chromeOptions.AddAdditionalCapability("accesskey", accesskey, true);
32
            chromeOptions.AddAdditionalCapability("build", "[C#] Locale Testing with Chrome & Windows on LambdaTest Selenium Grid", true);
33
            chromeOptions.AddAdditionalCapability("name", "[C#] Locale Testing with Chrome & Windows on LambdaTest Selenium Grid", true);
34
            chromeOptions.AddAdditionalCapability("version", "80.0", true);
35
            chromeOptions.AddAdditionalCapability("platform", "Windows 10", true);
36
 
37
            driver = new RemoteWebDriver(new Uri("https://" + username + ":" + accesskey + gridURL), chromeOptions.ToCapabilities(), TimeSpan.FromSeconds(600));
38
  
39
            System.Threading.Thread.Sleep(2000);
40
            driver.Url = "https://manytools.org/http-html-text/browser-language/";
41
 
42
            var executor = (IJavaScriptExecutor)driver;
43
            String language = executor.ExecuteScript("return window.navigator.userlanguage || window.navigator.language").ToString();
44
 
45
            language.Should().Be("he-IL");
46
            /* Perform wait to check the output */
47
            System.Threading.Thread.Sleep(2000);
48
        }
49
 
50
        [TearDown]
51
        public void Cleanup()
52
        {
53
            bool passed = TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Passed;
54
            try
55
            {
56
                //Logs the result to Lambdatest
57
                ((IJavaScriptExecutor)driver).ExecuteScript("lambda-status=" + (passed ? "passed" : "failed"));
58
            }
59
            finally
60
            {
61
                // Terminates the remote webdriver session
62
                driver.Quit();
63
            }
64
        }
65
    }
66
}


Code WalkT hrough

Step 1: The FluentAssertions package provides an extensive set of extension methods for checking the expected outcome (w.r.t locale). Hence, the FluentAssertions package is installed by executing the following command on the Package Manager Console.

Shell
 






The package is imported before it is used in the cod:

using FluentAssertions;

Step 2An instance of ChromeOptions is created. The AddArgument() method of ChromeOptions is used for setting the language to Hebrew (i.e. he-IL).

C#
 




xxxxxxxxxx
1


 
1
var chromeOptions = new ChromeOptions();
2
chromeOptions.AddArgument("--lang=he-IL");


Step 3: The chromeOptions.ToCapabilities() method is used for passing the required browser capabilities to the RemoteWebDriver interface.

The combination of user-name and access-key is used for accessing the Selenium Grid cloud on LambdaTest [@hub.lambdatest.com/wd/hub]

C#
 




xxxxxxxxxx
1


 
1
driver = new RemoteWebDriver(new Uri("https://" + username + ":" + accesskey + gridURL), chromeOptions.ToCapabilities(), TimeSpan.FromSeconds(600));


Step 4Like with Python, I use the ExecuteScript method for executing JavaScript code that returns the language of the browser window.

C#
 




xxxxxxxxxx
1


 
1
var executor = (IJavaScriptExecutor)driver;
2
String language = executor.ExecuteScript("return window.navigator.userlanguage || window.navigator.language").ToString();


Step 5The Should() method offered by FluentAssertions is used for checking whether the browser language is set to Hebrew (i.e. he-IL).

language.Should().Be("he-IL");

C#
 




xxxxxxxxxx
1
69


1
using System;
2
using System.Globalization;
3
using System.Reflection;
4
using System.Diagnostics;
5
using OpenQA.Selenium;
6
using OpenQA.Selenium.Remote;
7
using System.Threading;
8
using System.Collections.Generic;
9
using NUnit.Framework;
10
using OpenQA.Selenium.Chrome;
11
using OpenQA.Selenium.Firefox;
12
using FluentAssertions;
13
 
14
namespace ParallelLTSelenium
15
{
16
    [TestFixture]
17
    public class ParallelLTTests
18
    {
19
        IWebDriver driver;
20
 
21
        [Test]
22
        public void test_locale_firefox()
23
        {
24
            String username = "user-name";
25
            String accesskey = "access-key";
26
            String gridURL = "@hub.lambdatest.com/wd/hub";
27
 
28
            DesiredCapabilities capabilities = new DesiredCapabilities();
29
            var firefoxOptions = new FirefoxOptions();
30
            firefoxOptions.SetPreference("intl.accept_languages", "ja-JP");
31
 
32
            firefoxOptions.AddAdditionalCapability("user", username, true);
33
            firefoxOptions.AddAdditionalCapability("accesskey", accesskey, true);
34
            firefoxOptions.AddAdditionalCapability("build", "[C#] Locale Testing with Firefox & macOS on LambdaTest Selenium Grid", true);
35
            firefoxOptions.AddAdditionalCapability("name", "[C#] Locale Testing with Firefox & macOS on LambdaTest Selenium Grid", true);
36
            firefoxOptions.AddAdditionalCapability("version", "78.0", true);
37
            firefoxOptions.AddAdditionalCapability("platform", "macOS Mojave", true);
38
 
39
            driver = new RemoteWebDriver(new Uri("https://" + username + ":" + accesskey + gridURL), firefoxOptions.ToCapabilities(), TimeSpan.FromSeconds(600));
40
            //driver = new ChromeDriver(chromeOptions);
41
 
42
            System.Threading.Thread.Sleep(2000);
43
            driver.Url = "https://manytools.org/http-html-text/browser-language/";
44
 
45
            var executor = (IJavaScriptExecutor)driver;
46
            String language = executor.ExecuteScript("return window.navigator.userlanguage || window.navigator.language").ToString();
47
 
48
            language.Should().Be("ja-JP");
49
            /* Perform wait to check the output */
50
            System.Threading.Thread.Sleep(2000);
51
        }
52
 
53
        [TearDown]
54
        public void Cleanup()
55
        {
56
            bool passed = TestContext.CurrentContext.Result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Passed;
57
            try
58
            {
59
                //Logs the result to Lambdatest
60
                ((IJavaScriptExecutor)driver).ExecuteScript("lambda-status=" + (passed ? "passed" : "failed"));
61
            }
62
            finally
63
            {
64
                // Terminates the remote webdriver session
65
                driver.Quit();
66
            }
67
        }
68
    }
69
}


Code Walk Through

The implementation for Test Scenario 2 (that uses Firefox) only differs in the way the locale is set for the browser.

An instance of FirefoxOptions is created and the SetPreference() method is used for setting the browser locale to Japanese (i.e. ‘ja-JP’). intl.accept_languages is the preferences key for manipulating the language for the web page to ja-JP.

C#
 




xxxxxxxxxx
1


1
var firefoxOptions = new FirefoxOptions();
2
firefoxOptions.SetPreference("intl.accept_languages", "ja-JP");


For clarity, I have marked the code changes for running Test Scenario 1 and Test Scenario 2 using Java: 

Execution

We used Visual Studio Code 2019 (Community Edition) for creating a project and running the tests. Shown below is the execution snapshot of Internationalization in Selenium WebDriver from LambdaTest which indicates that the browser locale was set as expected:

WebDriver Internationalization With Selenium Java

The TestNG framework is used in the implementation for Selenium test automation. For a quick recap about the TestNG framework, you can refer to this detailed coverage on TestNG annotations.

Java
 




xxxxxxxxxx
1
65


1
package org.selenium4;
2
 
3
import org.openqa.selenium.By;
4
import org.openqa.selenium.JavascriptExecutor;
5
import org.openqa.selenium.WebDriver;
6
import org.openqa.selenium.WebElement;
7
import org.openqa.selenium.chrome.ChromeOptions;
8
import org.openqa.selenium.remote.RemoteWebDriver;
9
import org.testng.annotations.AfterClass;
10
import org.testng.annotations.BeforeClass;
11
import org.testng.annotations.Test;
12
import java.net.MalformedURLException;
13
import java.net.URL;
14
import static org.junit.Assert.*;
15
 
16
public class CrossBrowserTest {
17
    /* protected static ChromeDriver driver; */
18
    WebDriver driver = null;
19
    String URL = "https://manytools.org/http-html-text/browser-language/";
20
    public static String status = "passed";
21
    String username = "user-name";
22
    String access_key = "access-key";
23
 
24
    @BeforeClass
25
    public void testSetUp() throws MalformedURLException {
26
        ChromeOptions chromeOptions = new ChromeOptions();
27
        chromeOptions.addArguments("--lang=he-IL");
28
 
29
        chromeOptions.setCapability("build", "[Java] Locale Testing with Chrome & Windows on LambdaTest Selenium Grid");
30
        chromeOptions.setCapability("name", "[Java] Locale Testing with Chrome & Windows on LambdaTest Selenium Grid");
31
        chromeOptions.setCapability("platform", "Windows 10");
32
        chromeOptions.setCapability("browserName", "Chrome");
33
        chromeOptions.setCapability("version","80.0");
34
        chromeOptions.setCapability("tunnel",false);
35
        chromeOptions.setCapability("network",true);
36
        chromeOptions.setCapability("console",true);
37
        chromeOptions.setCapability("visual",true);
38
 
39
        driver = new RemoteWebDriver(new URL("http://" + username + ":" + access_key + "@hub.lambdatest.com/wd/hub"), chromeOptions);
40
        System.out.println("Started session");
41
    }
42
 
43
    @Test
44
    public void test_Selenium4_ToDoApp() throws InterruptedException {
45
        driver.navigate().to(URL);
46
        driver.manage().window().maximize();
47
 
48
        JavascriptExecutor executor = (JavascriptExecutor) driver;
49
        String language = executor.executeScript("return window.navigator.userlanguage || window.navigator.language").toString();
50
        /* driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); */
51
        /* Not a good programming practice, added for demonstration */
52
        Thread.sleep(5000);
53
 
54
        assertEquals(language, "he-IL");
55
        Thread.sleep(2000);
56
    }
57
 
58
    @AfterClass
59
    public void tearDown() {
60
        if (driver != null) {
61
            ((JavascriptExecutor) driver).executeScript("lambda-status=" + status);
62
            driver.quit();
63
        }
64
    }
65
}


Code Walk Through

Step 1: The TestNG framework is used for Selenium test automation, hence the necessary packages are included before I start with the implementation of Internationalization in Selenium WebDriver.

Java
 




xxxxxxxxxx
1


1
import org.testng.annotations.AfterClass;
2
import org.testng.annotations.BeforeClass;
3
import org.testng.annotations.Test;


Step 2: The implementation under the @BeforeClass annotation will be executed before the test case is triggered. Like the implementations in Python and C#, an instance of ChromeOptions is used and the addArguments() method is used for setting the language to ‘he-IL’.

Java
 




xxxxxxxxxx
1


1
ChromeOptions chromeOptions = new ChromeOptions();
2
chromeOptions.addArguments("--lang=he-IL");


Step 3: Test case implementation is included under the @Test annotation. JavaScript code is triggered using the interface offered by JavascriptExecutor. The executeScript method is used for getting the browser locale (i.e. window.navigator.userlanguage or window.navigator.language).

Java
 




xxxxxxxxxx
1


1
@Test
2
    public void test_Selenium4_ToDoApp() throws InterruptedException {
3
 ………………………………………..
4
 ………………………………………..
5
 JavascriptExecutor executor = (JavascriptExecutor) driver;
6
 String language = executor.executeScript("return window.navigator.userlanguage || window.navigator.language").toString();


Java
 




xxxxxxxxxx
1
69


1
package org.selenium4;
2
 
3
import org.openqa.selenium.By;
4
import org.openqa.selenium.JavascriptExecutor;
5
import org.openqa.selenium.WebDriver;
6
import org.openqa.selenium.WebElement;
7
import org.openqa.selenium.WebDriver;
8
import org.openqa.selenium.firefox.FirefoxOptions;
9
import org.openqa.selenium.firefox.FirefoxProfile;
10
import org.openqa.selenium.remote.DesiredCapabilities;
11
import org.openqa.selenium.remote.RemoteWebDriver;
12
import org.testng.annotations.AfterClass;
13
import org.testng.annotations.BeforeClass;
14
import org.testng.annotations.Test;
15
import java.net.MalformedURLException;
16
import java.net.URL;
17
import static org.junit.Assert.*;
18
 
19
public class CrossBrowserTest {
20
    WebDriver driver = null;
21
    String URL = "https://manytools.org/http-html-text/browser-language/";
22
    public static String status = "passed";
23
    String username = "user-name";
24
    String access_key = "access-key";
25
 
26
    @BeforeClass
27
    public void testSetUp() throws MalformedURLException {
28
        FirefoxOptions firefoxOptions = new FirefoxOptions();
29
        FirefoxProfile firefoxProfile = new FirefoxProfile();
30
        firefoxProfile.setPreference("intl.accept_languages", "ja-JP");
31
        firefoxOptions.setProfile(firefoxProfile);
32
 
33
        firefoxOptions.setCapability("build", "[Java] Locale Testing with Firefox & macOS on LambdaTest Selenium Grid");
34
        firefoxOptions.setCapability("name", "[Java] Locale Testing with Firefox & macOS on LambdaTest Selenium Grid");
35
        firefoxOptions.setCapability("platform", "macOS Mojave");
36
        firefoxOptions.setCapability("browserName", "Firefox");
37
        firefoxOptions.setCapability("version","78.0");
38
        firefoxOptions.setCapability("tunnel",false);
39
        firefoxOptions.setCapability("network",true);
40
        firefoxOptions.setCapability("console",true);
41
        firefoxOptions.setCapability("visual",true);
42
 
43
        driver = new RemoteWebDriver(new URL("http://" + username + ":" + access_key + "@hub.lambdatest.com/wd/hub"), firefoxOptions);
44
        System.out.println("Started session");
45
    }
46
 
47
    @Test
48
    public void test_Selenium4_ToDoApp() throws InterruptedException {
49
        driver.navigate().to(URL);
50
        driver.manage().window().maximize();
51
 
52
        JavascriptExecutor executor = (JavascriptExecutor) driver;
53
        String language = executor.executeScript("return window.navigator.userlanguage || window.navigator.language").toString();
54
        /* driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); */
55
        /* Not a good programming practice, added for demonstration */
56
        Thread.sleep(5000);
57
 
58
        assertEquals(language, "ja-JP");
59
        Thread.sleep(2000);
60
    }
61
 
62
    @AfterClass
63
    public void tearDown() {
64
        if (driver != null) {
65
            ((JavascriptExecutor) driver).executeScript("lambda-status=" + status);
66
            driver.quit();
67
        }
68
    }
69
}


Code Walk Through

The implementation for Test Scenario 2 differs in the way its locale is set. An instance of FirefoxOptions() is created so that the browser capabilities can be set.

Java
 




xxxxxxxxxx
1


 
1
@BeforeClass
2
    public void testSetUp() throws MalformedURLException {
3
        FirefoxOptions firefoxOptions = new FirefoxOptions();
4
      


An instance of FirefoxProfile() is created for a customized profile that suits our needs. The setPreference() method modifies the intl.accept_languageskey to ‘ja-JP’. 

Java
 




xxxxxxxxxx
1


1
@BeforeClass
2
    public void testSetUp() throws MalformedURLException {
3
        FirefoxOptions firefoxOptions = new FirefoxOptions();
4
        FirefoxProfile firefoxProfile = new FirefoxProfile();
5
        firefoxProfile.setPreference("intl.accept_languages", "ja-JP");


The modified profile is set using the setProfile() method of FirefoxOptions

Java
 




xxxxxxxxxx
1


 
1
firefoxOptions.setProfile(firefoxProfile);


Rest of the implementation is same as the one used for Test Scenario 1, the code changes are shown below for better understanding:

Execution

I used the IntelliJ IDEA IDE for creating a project and running the tests. Shown below is the execution snapshot from LambdaTest which indicates that the browser locale was set as expected:

Wrap Up

Internationalization testing is extremely important for companies that develop products for a global audience. The resources (i.e. strings, images, etc.) that are specific to a particular locale should be coupled less tightly from the resources that are used for the main target market. 

Before using Internationalization in Selenium WebDriver for automation testing, it is necessary to follow the i18n rules mentioned in the Internationalization testing checklist. Depending on the browser share for the primary target market, you should lay down a plan to use Selenium test automation for Internationalization testing of your web product. The options used in Internationalization in Selenium WebDriver depend on the browser on which the locale is set, hence, it is important to prioritize the testing on browsers that matter the most. 

Happy testing!

 

 

 

 

Top