How to change the language of a WebDriver?

后端 未结 3 1803
野性不改
野性不改 2020-12-14 02:35

I want to execute my Selenium tests in different languages. Is it possible to change the language of an existing WebDriver at runtime or do I have to recreate the browser in

3条回答
  •  清歌不尽
    2020-12-14 03:18

    I am afraid that the whole idea of WebDriver is to act like browser - so you can change the language of the browser, but you have to change the locale in the Operating system, or hope that the application will do it for you.

    For instance - German number format separates decimal number by comma and English one by dot. If you want to test, how the number format behaves in English locale and in German locale, you can do it only by these two approaches:

    1. Change OS locale from German to English or vice versa
    2. Change browser language and hope that application will change the behavior.

    To answer your questions:

    1. There is no setLocale on Webdriver, because WebDriver simulates browser, not OS
    2. I would do it like this (Java code):

      private WebDriver driver;  
      
      public enum Language {en-us, de}
      
      public WebDriver getDriver(Language lang){
        String locale = lang.toString();
        FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference("intl.accept_languages", locale);
        driver = new FirefoxDriver(profile);   
        return driver;       
      }
      
      @Test
      public void TestNumber(){
        WebDriver drv = getDriver(Language.en);
        drv.get("http://the-site.com");
        WebElement el = drv.findElement //... find element
        String number = el.getText();
        Assert.assertEquals(number, "123.45");
        drv.close();
        drv = getDriver(Language.de);
        drv.get("http://the-site.com");
        WebElement el = drv.findElement //... find element
        String number = el.getText();
        Assert.assertEquals(number, "123,45");
        drv.close();
      }
      
    3. I am afraid you have to close the browser and open it again with different language.

    4. I personally create new instance of the browser for each test.

    BTW the above bit of code assumes, that the web application changes the way how to show numbers to the user based on browser language.

提交回复
热议问题