Mastering Mockito for mocking org.openqa.selenium.support.ui.Select components

Unit testing is a vital part of my Selenium integration tests, and in order to effectively test them, I need the ability to mock the selenium Select Object.

The method I am testing:

protected int findOptionByIgnoreCaseText(String value, Select dropDown) {
...
}

My testing strategy involves:

@Test
public void testFindOptionByIgnoreCaseText() {
    WebElement mockElement = Mockito.mock(WebElement.class,....??? "Peter","Stéphane","Katy","Brad"
    Select dropDown = new Select(mockElement);
    Assert.assertEquals("OK", 1, step.findOptionByIgnoreCaseText("Peter", dropDown);
    Assert.assertEquals("OK", 2, step.findOptionByIgnoreCaseText("Stephane", dropDown);
    Assert.assertEquals("OK", 2, step.findOptionByIgnoreCaseText("Stéphane", dropDown);
    Assert.assertEquals("OK", 3, step.findOptionByIgnoreCaseText("Katy", dropDown);
   Assert.assertEquals("OK", 4, step.findOptionByIgnoreCaseText("Brad", dropDown);
}

Answer №1

In my search for the solution:

I referenced the official Selenium documentation here

@Test
public void testFindOptionByIgnoreCaseText() {
    final WebElement johnOption = mockOption("John");
    final WebElement emilyOption = mockOption("Emily");
    final WebElement noahOption = mockOption("Noah");
    final WebElement sophiaOption = mockOption("Sophia");
    final WebElement liamOption = mockOption("Liam ");
    final List<WebElement> options = Arrays.asList(johnOption, emilyOption, noahOption, sophiaOption, liamOption);

    final WebElement element = Mockito.mock(WebElement.class);
    Mockito.when(element.getTagName()).thenReturn("select");
    Mockito.when(element.findElements(By.tagName("option"))).thenReturn(options);
    Select select = new Select(element);

    Assert.assertEquals("OK", 0, step.findOptionByIgnoreCaseText("John", select));

    // Additional test cases omit to conserve space...

    Assert.assertEquals("OK", 4, step.findOptionByIgnoreCaseText("Liam ", select));
    Assert.assertEquals("OK", 4, step.findOptionByIgnoreCaseText(" Liam", select));

    // Additional test cases omit to conserve space...

}

private WebElement mockOption(String name) {
    final WebElement option = Mockito.mock(WebElement.class, name);
    Mockito.when(option.getText()).thenReturn(name);
    return option;
}

The method I tested is as follows:

protected int findOptionByIgnoreCaseText(String value, Select dropDown) {
    int index = 0;
    for (WebElement option : dropDown.getOptions()) {
        if (Normalizer.normalize(option.getText(), Normalizer.Form.NFD).replaceAll("[\\p{InCombiningDiacriticalMarks}]", "").trim()
                .equalsIgnoreCase(Normalizer.normalize(value, Normalizer.Form.NFD).replaceAll("[\\p{InCombiningDiacriticalMarks}]", "").trim())) {
            return index;
        }
        index++;
    }
    return -1;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

List out all the items present in the Selenium Python bindings specific to the Appium framework

As I begin my journey with Appium to test my company's mobile applications, I have decided to use the Python bindings for scripting, starting with Android apps. Successfully running the Appium examples with grunt android, and executing the android.py ...

Can you explain the discrepancy between the two sets of code below?

As I delve into the world of Java and selenium, I am eager to grasp the nuances between the two sets of code provided below. Surprisingly, both codes execute smoothly with identical behavior. WebDriver is an interface that is implemented by the FirefoxDri ...

What exactly does the Test Explorer initiate?

Currently, I am interested in performing tests on a web page front end that interacts with an ASP.NET RESTful Web API using Selenium. My understanding is that when I select "Run All" in the test explorer, it initiates my web server, opens my web page (re ...

Automating file downloads using Selenium for http://www.diva-gis.org/datadown

Currently, I am utilzing Selenium to automate the download process from a specific website: http://www.diva-gis.org/datadown While I have no issues clicking 'OK' on the initial page, I seem to encounter difficulty in clicking 'Download&apo ...

Even with the correct Step Definition in place, Cucumber is struggling to locate it

While setting up the Selenium Cucumber framework, I encountered a problem. Even though the step definition path is correctly defined in the glue, it somehow cannot locate the cucumber step definition. Here are the installed jars: Cucumber-java, Cucumber-c ...

Creating a fixed "sub-page" within Wicket (e.g.: linking a folder in Wicket)

I am in the process of creating a web application with the help of Wicket. While the majority of the website is generated dynamically through Wicket, I have a specific section that needs to function as a standalone "static" html website. Essentially, this ...

Guide to managing authentication popups in Chrome using Selenium WebDriver in Java

I'm currently dealing with an authentication pop-up in one of my new Webdriver scripts. While I have a solution that works for Internet Explorer, I'm facing some challenges with Chrome. The approach for IE was straightforward - following the guid ...

Error: The file or directory 'geckodriver' cannot be found for a basic Python Selenium program

I am currently experimenting with a basic selenium example on a Linux system: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("something") But I encountered an error: FileNotFoundEr ...

Ways to verify if certain text information is present on the webpage

Is there a specific way to determine if certain texts are present on a webpage? It would be ideal to check multiple texts at once. For instance, checking for "client", "customer", and "order" in the page content. Below is an example of the HTML code snip ...

Discover the art of shaping Allure's legacy

Is there a way to view the results of my Allure test scripts for Day 1 and Day 2, in addition to those from Day 3, after running them daily? The history tab does not load history data. ...

Converting int arrays into JSON for Spring RequestBody handling

I am facing an issue with my Spring controller method that requires a @RequestBody as a parameter. The structure of the request body class is like this: public class myClass { CustomObject obj int x int y int[] values Character c ...

The error message java.lang.NumberFormatException: Unable to parse the input string: "2017-01-28 13:28:20" occurred

During the execution of my java project, I encountered an error with a Gson deserializer function. The error message states: java.lang.NumberFormatException: For input string: "2017-01-28 13:28:20" at java.lang.NumberFormatException.forInputString(NumberF ...

Encountering a TimeoutException while utilizing Selenium in Python

Utilizing WebDriverWait in my script involves two different instances with the same syntax. The first time I use it is to check for any typos within a defined class, while the second time is under a function nested within the same class. Surprisingly, an e ...

Selenium failing to interact with element

Seeking help with clicking a checkbox element: <input checked="checked" class="iceSelBoolChkbx" id="mainContentId:newSerchCheckBox" name="mainContentId:newSerchCheckBox" onblur="setFocus('');" onclick="var form=formOf(this);iceSubmitPartia ...

Having trouble retrieving the value of the second dropdown in a servlet through request.getParameter

I am facing an issue with storing the value of the second dropdown in a servlet after utilizing an ajax call in Java to populate it based on the selection made in the first dropdown. While I was able to successfully store the value of the first dropdown ...

Selenium - How to pass a file path to a dynamically generated input element that is not visible in the DOM

Check out this example of HTML code: This is how you create a visible button and display the selected file: <button id="visible-btn">visible button</button> <p>selected file is: <span id="selected-file"></spa ...

Selenium was unable to find the email input field as it is not contained within any iframe

I have been attempting to find the login ID and password fields on a specific website: However, it seems that Selenium is unable to locate the email input box. I have searched on StackOverflow for a solution but unfortunately, haven't found any. One ...

Having trouble with closing the login window or accessing the HomePage on makeMyTrip.com

As I attempt to automate the MakeMyTrip website using selenium, a snag I've encountered is that the login window ends up blocking all other elements on the page when running tests. One approach I took was trying to click elsewhere on the page in an e ...

Using Selenium Webdrivers to Browse Pages with Minimal Resource Loading

I'm attempting to restrict Javascript from altering the source code of the site while testing with Selenium. Disabling Javascript completely in the Webdriver is not an option as I require it for testing purposes. Below is my approach for the Firefox W ...

What are some methods to execute a line of code in the event that the button is not present within my IF statement

After receiving assistance from a member on this platform, I managed to get this code to function correctly: boolean clickMore = true; while(clickMore == true) { List<WebElement> button1 = driver.findElements(By ...