Skip to main content

You are here

Assert if an option exists on a menu

This is kind of a crude method but its worked. This is an extention of the codes shown in the previous post. I mentioned I would re-write the codes to check for the presence of a text or option in a menu.

I have set reference to TestNG on this one. So in addition to the Selenium library, the TestNG library should be referenced as well.

The stepts I have adopted include:

1. Loop through an extracted list of menu options
2. Match each item to the expected text "Forums"
3. Set a variable to 1 when a match is found.
4. Using TestNG Assert class to ensure the variable in step 3 is equal to 1

The follwing line does a comparison between the value of the variable in step 3 to the expected result of 1 (found). If these 2 values don match, an exception is thrown. Test fails.

Assert.assertEquals(foundIt,1);

Am sure there is way to check the list variable: menuOptions without having to loop through each item. I will leave that for any visiting guru to tell us.
Otherwise, this is my crude approachh to this test:

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;

public class AssertMenuOptionsText {
public static void main(String[] args) {
int foundIt = 0;  // make equal to zero. It will become 1 if we find the menu item in loop below

WebDriver driver = new FirefoxDriver(); // or some other driver
driver.get("http://www.sojicity.com");
WebElement mainMenu = driver.findElement(By.id("main-menu"));
List<WebElement> menuOptions = mainMenu.findElements(By.tagName("a"));

System.out.println(menuOptions.size() + " menu options found!");

// this portion just lists off all the found menu options
for (int i = 0; i < menuOptions.size(); i++) {
System.out.println(menuOptions.get(i).getText());
if (menuOptions.get(i).getText().equals("Forumss"))  // I deliberately misspell Forums to allow program throw exception
foundIt = 1;  // set to 1 once we find the menu item
}

// Using TestNG Assert, I check it variable foundIt is 1
Assert.assertEquals(foundIt,1);

driver.quit();
}
}

Let me know what you think or send an alternative code doing the same stuff.

Tags: 

Category: 

Language: 

0
No votes yet

Add new comment

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.

Disclaimer

Note that the codes and ideas expressed on this site are the authors personal views. The content of this website are the personal notes based on the learning experience of the author. The author will not be responsible for any error or damages resulting from you using the content of this website.

Premium Drupal Themes by Adaptivethemes