Web code samples (Java SDK)
Send keystrokes to the AUT
// Describe the search edit field EditField ef = browser.describe(EditField.class, new EditFieldDescription.Builder() .type("text").tagName("INPUT").name("_nkw").build()); // Type "ft" in the search box ef.setValue("ft"); // Use the Mouse class to click on the edit field java.awt.Point abs = ef.getAbsoluteLocation(); java.awt.Point p = new java.awt.Point(abs.x + 5, abs.y + 5); Mouse.click(p); // Use the Keyboard class to send the Enter key Keyboard.pressKey((byte)28);
Navigate to a web site
This example uses the Verify command to verify navigation to a web site.
@Test public void verify_linkNavigatesToAboutTravelSite() throws Exception { // Launch the Chrome browser. Browser browser = BrowserFactory.launch(BrowserType.CHROME); try { // Navigate to the Advantage Online Shopping website. browser.navigate("http://advantageonlineshopping.com/#/"); // Click the "Speakers" link (in the top-left side of the page). browser.describe(Link.class, new LinkDescription.Builder() .innerText("SPEAKERS Shop Now ") .tagName("DIV").build()).click(); // Wait for the browser to complete the navigation. browser.sync(); // Verify that the correct Web page opens. Verify.areEqual("http://advantageonlineshopping.com/#/category/Speakers/4", browser.getURL(), "Verify_linkNavigatesSpeakersSite", "Verify that the browser's URL is as expected."); } catch (Error e) { Reporter.reportEvent("Verify_SpeakersOpensCorrectly", "Failed during test", Status.Failed, e); throw e; } finally { browser.close(); } }
Access Web objects in a tab opened by the AUT
OpenText Functional Testing for Developers recognizes browser windows and tabs that it opens (for example, via BrowserFactory.Launch).
However, if a browser is opened outside of the OpenText Functional Testing for Developers context, you need to use the Attach method to acquire the IBrowser Interface instance for the browser tab or window.
For example, you need to attach a browser if:
- You open a browser manually while setting up a scenario prior to running a test
- A step in your test clicks a link that opens a new or replacement browser tab or window
This example attaches a newly opened browser tab.
@Test public void Verify_AccessWebObjectsInTabOpenedByAUT() throws Exception { //Launch the Chrome browser. Browser browser = BrowserFactory.launch(BrowserType.CHROME); // Use Try/Catch to add a warning to the run report if the validation fails. try{ //Navigate to the Advantage Online Shopping website. browser.navigate("http://advantageonlineshopping.com/"); // Click the "Speakers" link (on the left side of the page). browser.describe(Link.class, new LinkDescription.Builder() .innerText("SPEAKERS Shop Now ") .tagName("DIV").build()).click(); //Attach the new (replacement) browser tab. Browser aboutTab = BrowserFactory.attach(new BrowserDescription.Builder().title("Advantage Shopping").build()); //Create a description for the page. Page aboutTitle = aboutTab.describe(Page.class, new PageDescription.Builder() .title("Advantage Shopping").index(0).build()); //Validate that a page title exists. Verify.isTrue(aboutTitle.exists(), "Verify_AccessWebObjectsInTabOpenedByAUT", "Validate that the title page exists."); } catch(Error e){ // Add a log message to the results report on failure. Reporter.reportEvent("Verify_AboutOpensCorrectly","Failed during test",Status.Failed, e); throw e; } finally{ browser.close(); } }
Use Verify to validate a successful log in
This example validates the success of a log in operation by checking for the account name at the top of the screen.
@Test public void verify_UserCanSuccessfullyLogIn() throws Exception { // Navigate to the Advantage Online Shopping website. Browser browser = BrowserFactory.launch(BrowserType.CHROME); browser.navigate("http://advantageonlineshopping.com/"); try{ // Open the menu to navigate to the log in option. Link userMenuLink = browser.describe(Link.class, new LinkDescription.Builder() .cssSelector("a#menuUserLink") .tagName("A").build()); userMenuLink.click(); // Log in to the web site. EditField username = browser.describe(EditField.class, new EditFieldDescription.Builder() .type("text").name("userName").build()); EditField password = browser.describe(EditField.class, new EditFieldDescription.Builder() .type("password").name("password").build()); // Set the username and password. username.setValue("MyName"); password.setValue("55940Fd62c96"); // Click the SIGN IN button. browser.describe(Button.class, new ButtonDescription.Builder() .buttonType("button") .name("SIGN IN") .tagName("BUTTON").build()).click(); //Verify that user name appears in the top-right corner after logging in. Verify.isTrue(userMenuLink.getInnerText().contains("MyName"), "Verify_UserCanSuccessfullyLogIn", "Verify that user name appears in the top-right corner after logging in."); } catch(Error e){ Reporter.reportEvent("Verify_UserCanSuccessfullyLogIn","Failed during test",Status.Failed, e); throw e; } finally{ browser.close(); } }
Identify an object by its XPath
This example locates the login button using it's XPath and then verifies that the credential fields are visible.
@Test public void verify_IdentifyLoginButtonByXPath() throws Exception { // Identify the user login using XPath and verify the login dialog.// Open the Chrome browser. Browser browser = BrowserFactory.launch(BrowserType.CHROME); // Use try-catch to add a warning to the run report if the Verify validation fails. try { // Navigate to the Advantage Online Shopping website browser.navigate("http://advantageonlineshopping.com/"); // Locate the login button using its XPath. Link userMenuLink = browser.describe(Link.class, new XPathDescription("//A[@id=\"menuUserLink\"]")); userMenuLink.highlight(); userMenuLink.click(); // Enclosing the Verify method in a try-catch statement ensures the application does not throw a // runtime error if the Verify returns false. Verify that the log in fields are visible EditField username = browser.describe(EditField.class, new EditFieldDescription.Builder() .type("text").name("userName").build()); EditField password = browser.describe(EditField.class, new EditFieldDescription.Builder() .type("password").name("password").build()); Verify.isTrue(username.exists(), "Verify_IdentifyLoginButtonByXPath", "Verify that user name field is visible after identifying the login button after XPath."); Verify.isTrue(password.exists(), "Verify_IdentifyLoginButtonByXPath", "Verify that password field is visible after identifying the login button after XPath."); } catch(Error e){ // Adds a step to the results report on failure. Reporter.reportEvent("Verify_IdentifyLoginButtonByXPath", "Failed during validation",Status.Failed, e); throw e; } finally{ browser.close(); } }
Identify an edit box via a CSS selector
This example shows how to verify that a suggestion box opens when a value is entered in a search box.
It includes:
- Firing an event that triggers the opening of a suggestion box
- Identifying the suggestion box using a CSS selector
- Using a WaitUntil statement to ensure that the suggestion box opens before continuing
- Using a Verify command to validate that the suggestion box opens
- Using a try-catch statement to add a message to the report if the validation fails
@Test public void verify_SearchSuggestionsAreOpenUponUserInput() throws Exception{ //Launch the Chrome browser and navigate to the web site. Browser browser = BrowserFactory.launch(BrowserType.CHROME); browser.navigate("http://www.google.com"); // Use Try/Catch to add a warning to the run report if the validation fails. try { // Enter the value "Some Text" in the search box. EditField search = browser.describe(EditField.class,new EditFieldDescription.Builder().name("q").build()); search.setValue("Some Text"); // Simulate a single key down event to trigger the opening of the suggestion box. search.fireEvent(EventInfoFactory.createEventInfo("onkeydown")); // Wait until the suggestion box opens. WebElement suggestions = browser.describe(WebElement.class,new CSSDescription(".sbsb_a")); WaitUntilTestObjectState.waitUntil(suggestions,new WaitUntilEvaluator<WebElement>(){ public boolean evaluate(WebElement suggestionBox){ try{ return suggestionBox.exists() && suggestionBox.isVisible(); } catch(Exception e){ return false; } } }); // Verify that the suggestion box exists. Verify.isTrue(suggestions.exists(), "Verify Search Suggestions UserInput Control Exists", "Verify that the suggestion box exists."); Verify.isTrue(suggestions.isVisible(), "Verify Search Suggestions UserInput Control Is Visible", "Verify that the suggestion box is visible."); } catch(Error e){ // Use a ReportEvent step to add details to the run report if the validation fails. Reporter.reportEvent("verify_SearchSuggestionsAreOpenUponUserInput","Failed during test",Status.Failed, e); throw e; } finally{ browser.close(); } }
Retrieve list items and print them
The following example shows how to retrieve values from a list and print them.
The test signs in to the AUT, adds some items to the shopping cart, and then prints the values to the console.
@Test public void verify_retrieveShoppingCartValues() throws Exception { // The test goes to the AUT, adds some items to the shopping cart, and then prints the values to the console. //Open the Chrome browser. Browser browser = BrowserFactory.launch(BrowserType.CHROME); // Navigate to the Advantage Online Shopping website. browser.navigate("https://www.advantageonlineshopping.com"); // Navigate to the "Speakers" link (on the top-left side of the page). browser.describe(Link.class, new LinkDescription.Builder() .innerText("SPEAKERS Shop Now ") .tagName("DIV").build()).click(); // Click the Bose Soundlink Bluetooth Speaker III item. WebElement boseSoundlinkBluetoothSpeaker = browser.describe(WebElement.class, new WebElementDescription.Builder() .innerText("SOLD OUT SHOP NOW Bose Soundlink Bluetooth Speaker III $269.99 ") .tagName("LI").build()); boseSoundlinkBluetoothSpeaker.click(); // Identify the "ADD TO CART" button. Button saveToCartButton = browser.describe(Button.class, new ButtonDescription.Builder() .buttonType("submit") .name("ADD TO CART") .tagName("BUTTON").build()); // Add the selected item to cart. saveToCartButton.click(); // Navigate back to speakers. Link speakersLink = browser.describe(Link.class, new LinkDescription.Builder() .innerText("SPEAKERS ") .tagName("A").build()); speakersLink.click(); // Click the Bose SoundLink Wireless Speaker item. WebElement boseSoundLinkWirelessSpeaker = browser.describe(WebElement.class, new WebElementDescription.Builder() .innerText("SOLD OUT SHOP NOW Bose SoundLink Wireless Speaker $129.00 ") .tagName("LI").build()); boseSoundLinkWirelessSpeaker.click(); // Add the selected item to cart. saveToCartButton.click(); // Go to the shopping cart. browser.describe(Link.class, new LinkDescription.Builder() .accessibilityName("ShoppingCart") .role("link") .tagName("A").build()).click(); Table shoppingCartTable = browser.describe(Table.class, new TableDescription.Builder() .index(1) .role("") .tagName("TABLE").build()); // Identify the items in the shopping cart Table element. TableRow wirelessSpeakerCartRow = shoppingCartTable.findRowWithCellText("WIRELESS"); TableRow bluetoothSpeakerCartRow = shoppingCartTable.findRowWithCellText("BLUETOOTH"); // Print the shopping cart cells to the console. for (TableCell cell: wirelessSpeakerCartRow.getCells()) { System.out.println("cellText: " + cell.getText() + " "); } for (TableCell cell: bluetoothSpeakerCartRow.getCells()) { System.out.println("cellText: " + cell.getText() + " "); } // Close the browser. browser.close(); }
Retrieve and validate list values
This example retrieves items from a drop-down list in the application and validates their values.
@Test public void verify_RetrieveProductCategoriesFromProductsListBox() throws Exception { // Open the Chrome browser. Browser browser = BrowserFactory.launch(BrowserType.CHROME); try { // Navigate to the Advantage Online Shopping website. browser.navigate("https://www.advantageonlineshopping.com/"); // Navigate to the "CONTACT US" link browser.describe(Link.class, new LinkDescription.Builder() .innerText("CONTACT US") .tagName("A").build()).click(); // Identify the product categories list box ListBox categoryListBox = browser.describe(ListBox.class, new ListBoxDescription.Builder() .name("categoryListboxContactUs") .tagName("SELECT").build()); // Get the list items to verify. ListItem laptopListItem = categoryListBox.getItems().get(1); ListItem headphonesListItem = categoryListBox.getItems().get(2); // Verify that the list items correspond with the expected values. Verify.areEqual(laptopListItem.getText(), "Laptops", "verify_RetrieveProductCategoriesFromProductsListBox", "Verify that the first category is \"Laptops\""); Verify.areEqual(headphonesListItem.getText(), "Headphones", "verify_RetrieveProductCategoriesFromProductsListBox", "Verify that the second category is \"Headphones\""); } catch(Error e){ Reporter.reportEvent("verify_RetrieveProductCategoriesFromProductsListBox", "Failed during test",Status.Failed, e); throw e; } finally{ browser.close(); } }
Verify a suggestion box contains values
This example shows how to verify that a suggestion box contains suggestions. This test:
- Navigates to the AUT.
- Opens the suggestion box from the search box.
- Waits until the suggestion box opens.
- Verifies that the suggestion box contains at least one suggestion.
@Test public void verify_SearchSuggestionsAreOpenUponUserInputAndShowsSuggestions() throws Exception{ // The test navigates to the AUT, opens the suggestion box from the search box, waits until the suggestion box opens, // and verifies that the suggestion box contains at least one suggestion. //Launch the Chrome browser and navigate to the web site. Browser browser = BrowserFactory.launch(BrowserType.CHROME); browser.navigate("http://www.google.com"); try { //Enter the value "Some Text" in the search box. EditField search = browser.describe(EditField.class,new EditFieldDescription.Builder().name("q").build()); search.setValue("Some Text"); //Simulate a single key down event to trigger the opening of the suggestion box. search.fireEvent(EventInfoFactory.createEventInfo("onkeydown")); //Identify the suggestion box using a CSS selector and wait until the suggestion box opens. WebElement suggestions = browser.describe(WebElement.class,new WebElementDescription.Builder().cssSelector(".sbsb_a").build()); WaitUntilTestObjectState.waitUntil(suggestions,new WaitUntilEvaluator<WebElement>(){ public boolean evaluate(WebElement suggestionBox){ try{ return suggestionBox.exists() && suggestionBox.isVisible(); } catch(Exception e){ return false; } } }); WebElement[] suggestionList = suggestions.findChildren(WebElement.class, new WebElementDescription.Builder().tagName("LI").build()); //Verify that the suggestion box exists and contains content. Verify.isTrue(suggestions.isVisible(), "Verify_SearchSuggestionsAreOpenUponUserInput", "Verify suggestion box exists."); Verify.greater(suggestionList.length, 0, "Verify_SearchSuggestionsAreOpenUponUserInput", "Verify suggestion box contains content."); } catch(Error e){ // Use a ReportEvent step to add details to the run report if the validation fails. Reporter.reportEvent("verify_SearchSuggestionsAreOpenUponUserInput","Failed during test",Status.Failed, e); browser.close(); throw e; } }
Identify an object using Visual Relation Identifiers (VRI)
This example shows how to use a symbol near a control in order to identify the control instead of using the control's properties.
This is helpful for controls that are generic, but are marked by specific symbols.
@Test public void Verify_MenuHelpItemUsingVRI() throws Exception { // In order to identify the help expand arrow in the top-right corner, // We use the question mark symbol that is next to the arrow. // Open the Chrome browser and navigate to the Advantage Online Shopping website. Browser browser = BrowserFactory.launch(BrowserType.CHROME); browser.navigate("https://www.advantageonlineshopping.com/"); try { // Define the the question mark element next to the help expand arrow. WebElement menuHelpWebElement = browser.describe(WebElement.class, new WebElementDescription.Builder() .accessibilityName("") .index(5) .innerText("") .tagName("svg").build()); // Define the visual relation identifier for the arrow, adding the test object described above. VisualRelation menuHelpVRI = new VisualRelation(); menuHelpVRI.setHorizontalRelation(HorizontalVisualRelation.RIGHT); menuHelpVRI.setTestObject(menuHelpWebElement); menuHelpVRI.setProximityRelation(ProximityVisualRelation.CLOSEST_ON_X_AXIS); // Define the help arrow object using the VRI. Image downArrowImage = browser.describe(Image.class, new ImageDescription.Builder() .vri(menuHelpVRI).build()); // Verify that the icon is visible. Verify.isTrue(downArrowImage.isVisible(), "Verify_MenuHelpItemUsingVRI", "Verify that the menu help icon is visible using VRI."); } catch (Error e) { Reporter.reportEvent("Verify_MenuHelpItemUsingVRI", "Failed during test", Status.Failed, e); throw e; } finally { browser.close(); } }
Verify objects using HTML attributes
This example gets all the images in the AUT's main page and verifies that all images contain the tagName attribute.
Note: This test should fail, as not all images on this page have a tagName attribute.
@Test public void verify_AllImagesContainTagNameAttribute() throws Exception { // Launch the Chrome browser and navigate to the Advantage Online Shopping website. Browser browser = BrowserFactory.launch(BrowserType.CHROME); browser.navigate("https://www.advantageonlineshopping.com/"); try { // Click the "Speakers" link (on the left side of the page). browser.describe(Link.class, new LinkDescription.Builder() .innerText("SPEAKERS Shop Now ") .tagName("DIV").build()).click(); List<Image> images = new ArrayList(Arrays.asList(browser.getPage().findChildren(Image.class, new ImageDescription.Builder() .alt("") .tagName("IMG") .type(com.hp.lft.sdk.web.ImageType.NORMAL).build()))); for(Image image : images){ Verify.isNotNullOrEmpty(image.getAttribute("tagName"), "verify_AllImagesContainTagNameAttribute", "Verify that the images have the \"tagName\" attribute. "); } } catch (Error e) { Reporter.reportEvent("verify_AllImagesContainTagNameAttribute", "Failed during test", Status.Failed, e); throw e; } finally { browser.close(); } }
Use JavaScript to check that spell check is enabled
This example shows how to inject JavaScript code into your webpage to verify that the spell check functionality is enabled.
@Test public void verify_suggestionBoxIsUsingSpellcheck() throws Exception { //Launch the Chrome browser and navigate to google.com. Browser browser = BrowserFactory.launch(BrowserType.CHROME); browser.navigate("http://www.google.com"); try { //Use the JavaScript spellcheck property to determine if the spell check is enabled. String performSpellCheck = browser.getPage().runJavaScript("document.querySelectorAll('.sbdd_b')[0].spellcheck.toString();"); Verify.isTrue(Boolean.parseBoolean(performSpellCheck), "Verify_UserCanEnterCredentialsAfterSignOff", "Verify that the spell check is enabled."); } catch (Error e) { Reporter.reportEvent("Verify_UserCanEnterCredentialsAfterSignOff", "Failed during test", Status.Failed, e); throw e; } finally { browser.close(); } }
Find an element by using regular expressions
This example uses the Describe method to create a regular expression to locate an object.
@Test public void verify_FindElementByRegex() throws Exception { // Launch the Chrome browser and navigate to the Advantage Online Shopping website. Browser browser = BrowserFactory.launch(BrowserType.CHROME); browser.navigate("https://www.advantageonlineshopping.com"); // Find the "Speakers" category element by Regex. WebElement speakersElement = browser.describe(WebElement.class, new WebElementDescription.Builder() .id(new RegExpProperty("speakers.*")) .className(new RegExpProperty(".*category.*")).build()); //Verifies that the element is found. Verify.isTrue(speakersElement.exists(), "verify_FindElementByRegex", "Verify that the \"Speakers\" category element is found."); }
Wait for a button to exist and be enabled
This example shows waiting for a button to exist and be enabled.
@Test public void newSynchronizationMethodsExamples() throws Exception { //Launch the Chrome browser. Browser browser = BrowserFactory.launch(BrowserType.CHROME); //Navigate to the Advantage Online Shopping website. browser.navigate("http://www.advantageonlineshopping.com/#/"); //Click the TABLETS image link Link tabletsShopNowLink = browser.describe(Link.class, new LinkDescription.Builder() .innerText("TABLETS Shop Now ") .tagName("DIV").build()); tabletsShopNowLink.click(); Button buyNowButton = browser.describe(Button.class, new ButtonDescription.Builder() .buttonType("submit") .name("BUY NOW") .tagName("BUTTON").build()); boolean buyNowButtonExists = buyNowButton.waitUntilExists(); if (!buyNowButtonExists) throw new GeneralLeanFtException("The buy now button does not exist"); boolean buyNowButtonEnabled = buyNowButton.waitUntilEnabled(); if (!buyNowButtonEnabled) throw new GeneralLeanFtException("The buy now button is not enabled"); boolean buyNowButtonVisible = buyNowButton.waitUntilVisible(); if (!buyNowButtonVisible) throw new GeneralLeanFtException("The buy now button is not visible"); }
See also: