Open topic with navigation

# Web code samples (Java SDK)

In this topic:

## 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);

Back to top

## 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 New Tours website.
    		browser.navigate("http://newtours.demoaut.com/");

    		//Click the "Business Travel @ About.com" link (in the bottom-right corner of the page).
    		browser.describe(Link.class, new LinkDescription.Builder()
    			.tagName("A").innerText("Business Travel @ About.com").build()).click();

    		//Wait for the browser to complete the navigation.
    		browser.sync();

    		//Verify that the correct Web page opens.
    		Verify.areEqual("http://businesstravel.about.com/?PM=78_101_T&cob=home", browser.getURL(), "Verify_linkNavigatesToAboutTravelSite", "Verify that the browser's URL is as expected.");
    	}
    	catch(Error e){
    		Reporter.reportEvent("Verify_AboutOpensCorrectly","Failed during test",Status.Failed, e);
    		throw e;
    	}
    	finally{
    		browser.close();
    	}
    }

Back to top

## Access Web objects in a tab opened by the AUT

LeanFTrecognizes browser windows and tabs that it opens (for example, via BrowserFactory.Launch).

However, if a browser is opened outside of the LeanFTcontext, 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 LeanFT 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_AboutOpensCorrectly() 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 New Tours website.
    		browser.navigate("http://newtours.demoaut.com/");

    		// Click the "Cruises" link (on the left side of the page).
    		browser.describe(Link.class, new LinkDescription.Builder()
    			.tagName("A").innerText("Cruises").build()).click();

    		//Attach the new (replacement) browser tab.
    		Browser aboutTab = BrowserFactory.attach(new BrowserDescription.Builder().title("Cruises: Mercury Tours").build());

    		//Create a description for the page title.
    		WebElement aboutTitle = aboutTab.describe(WebElement.class, new WebElementDescription.Builder()
    			.tagName("LI").innerText("Cruises").index(0).build());

    		//Validate that a page title exists.
    		Verify.isTrue(aboutTitle.exists(), "Verify_AboutOpensCorrectly", "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();
    	}
    }

Back to top

## Use Verify to verify edit fields

This example validates the status of edit fields for logon credentials after inserting the credentials at least once.

    @Test
    public void verify_UserCanEnterCredentialsAfterSignOff() throws Exception {

    	//Navigate to the New Tours website.
    	Browser browser = BrowserFactory.launch(BrowserType.CHROME);
    	browser.navigate("http://newtours.demoaut.com/");

    	try{
    		//Log on 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());

    		username.setValue("mercury");
    		password.setValue("55940fd62c96a30a62b4ab4d3db57c430de69cde");
    		browser.describe(Image.class, new ImageDescription.Builder()
    			.alt("Sign-In").type(com.hp.lft.sdk.web.ImageType.BUTTON).tagName("INPUT").build()).click();

    		//Log off.
    		browser.describe(Link.class, new LinkDescription.Builder()
    			.innerText("SIGN-OFF").build()).click();

    		//Verify that user name and password fields are writable after logging off.
    		Verify.isFalse(username.isReadOnly(), "Verify_UserCanEnterCredentialsAfterSignOff", "Verify that the 'userName' field is not read only.");
    		Verify.isFalse(password.isReadOnly(), "Verify_UserCanEnterCredentialsAfterSignOff", "Verify that the 'password' field is not read only.");
    	}
    	catch(Error e){
    		Reporter.reportEvent("verify_UserCanEnterCredentialsAfterSignOff","Failed during test",Status.Failed, e);
    		throw e;
    	}
    	finally{
    		browser.close();
    	}
    }

Back to top

## Identify an object by its XPath

This example will use a label's XPath to locate it and verify that the text represents the current date.

    @Test

    public void verify_CurrentDateIsPresented() throws Exception {

     // Suppose you want to verify that the AUT's home page displays today's date, but the date label does not have identification properties, and the text is dynamic.

     // You can use the label's XPath to locate it and verify that the text represents the current date.

     //Open the Chrome browser.

     Browser browser = BrowserFactory.launch(BrowserType.CHROME);

     // Use try-catch to add a warning to the run report if the assert validation fails.

     try

     {

      // Navigate to the New Tours website.

      browser.navigate("http://newtours.demoaut.com/");

      // Locate the label using its XPath.

      WebElement dateLabel = browser.describe(WebElement.class,

       new XPathDescription("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/form/table/tbody/tr[1]/td/font/b"));

      // Convert the date into a Java object.

      DateFormat df = new SimpleDateFormat("MMM d, yyyy",Locale.ENGLISH);

      Date presentedDate = (Date) df.parse(dateLabel.getInnerText().trim());;

      // Enclosing the Assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.

      // Verify that today's date matches the date displayed.

      Date currentDate = new Date();

      // Enclosing the assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.

      assertEquals(currentDate.getDate(),presentedDate.getDate());

     }

     catch(AssertionError e){

      // Adds a step to the results report on failure.

      Reporter.reportEvent("verify_CurrentDateIsPresented","Failed during validation",Status.Failed, e);

      throw e;

     }

     finally{

      browser.close();

     }

    }

Back to top

## 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 an Assert 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 assert validation fails.
    	try
    	{
    		// Enter the value "LeanFT" in the search box.
    		EditField search = browser.describe(EditField.class,new EditFieldDescription.Builder().name("q").build());
    		search.setValue("LeanFT");
    		// 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;
    				}
    			}
    		});

    		// Use Assert to 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();
    	}

    }

Back to top

## Retrieve and sort list items

This example shows how to retrieve a list from a combo box and sort the results.

The test will:

1. Sign in to the AUT.
2. Retrieve the list of departure cities.
3. Sort the list by the city name.
4. Verify that both the original list and the sorted one are identical.

    @Test
    public void verify_departureListIsSorted() throws Exception {
    	// The test will sign in to the AUT, retrieve the list of departure cities, and sort the list.
    	// Then it will sort the list by the city name and verify that both the original list and the sorted one are identical.

    	//Open the Chrome browser.
    	Browser browser = BrowserFactory.launch(BrowserType.CHROME);

    	try
    	{
    		//Navigate to the New Tours website.
    		browser.navigate("http://newtours.demoaut.com/");

    		//Log on to the web site.
    		signIn(browser);

    		// Retrieve a list of departure cities.
    		ListBox departureCombo = browser.describe(ListBox.class,new ListBoxDescription.Builder().tagName("SELECT").name("fromPort").build());

    		//Sort the list of cities.
    		List<ListItem> departureCities = departureCombo.getItems();
    		List<ListItem> sortedList = new ArrayList<ListItem>(departureCities);
    		Collections.sort(sortedList, new Comparator<ListItem>(){

    			@Override
    			public int compare(ListItem arg0, ListItem arg1) {
    				try {
    					return arg0.getText().compareToIgnoreCase(arg1.getText());
    				} catch (GeneralLeanFtException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    				return 0;
    				}
    			}
    		});

    		//Compares the two lists to verify that the data is identical.
    		Verify.areEqual(departureCities, sortedList, "verify_CitiesAreSorted", "Verify the data in the two lists is identical.");
    	}
    	catch (Error e)
    	{
    		Reporter.reportEvent("verify_CitiesAreSorted", "Failed during validation", Status.Failed, e);
    		throw e;
    	}
    	finally
    	{
    		browser.close();
    	}
    }

Back to top

## Retrieve and validate table values

This example will validate values in a table in the main page of the application.

    @Test
    public void verify_PriceIsPresentedInTheSpecialOffers() throws Exception {
    	//The test checks each row in the "special offers" table and verifies that the currency values are listed in dollars.

    	//Open the Chrome browser.
    	Browser browser = BrowserFactory.launch(BrowserType.CHROME);

    	try
    	{
    		//Navigate to the New Tours website.
    		browser.navigate("http://newtours.demoaut.com/");

    		Table specialOffers = browser.describe(Table.class,new TableDescription.Builder().tagName("TABLE").index(9).build());

    		//Find the rows in the Special Offers table and retrieves the currency values.
    		for (TableRow offer : specialOffers.getRows())
    		{
    			Verify.isTrue(offer.getCells().get(1).getText().startsWith("$"), "verify_PriceIsPresentedInTheSpecialOffers", "Verify currency values are in Dollars.");
    		}
    	}
    	catch(Error e){
    		Reporter.reportEvent("verify_PriceIsPresentedInTheSpecialOffers","Failed during test",Status.Failed, e);
    		throw e;
    	}
    	finally{
    		browser.close();
    	}
    }

Back to top

## Verify a suggestion box contains values

This example shows how to verify that a suggestion box contains suggestions. This test:

1. Navigates to the AUT.
2. Opens the suggestion box from the search box.
3. Waits until the suggestion box opens.
4. 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 "LeanFT" in the search box.
    		EditField search = browser.describe(EditField.class,new EditFieldDescription.Builder().name("q").build());
    		search.setValue("LeanFT");
    		//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;
    	}
    }

Back to top

## Identify an object using Visual Relation Identifiers (VRI)

This example signs in to the AUT and checks the edit field values using visual relation identifiers.

Since the edit fields are automatically generated IDs we cannot use the identification properties.

    @Test
    public void Verify_SignInIsAvailable() throws Exception{

    	//In order to identify the fields we will use the labels that are next to the fields in order to identify them.

    	//Open the Chrome browser and navigate to the New Tours Web site.
    	Browser browser = BrowserFactory.launch(BrowserType.CHROME);
    	browser.navigate("http://newtours.demoaut.com/");
    	try
    	{
    		//Define the labels that will be used for identifications of the fields.
    		WebElement usernameLabel = browser.describe(WebElement.class,new WebElementDescription.Builder().tagName("TD").innerText("User Name:").build());
    		WebElement passwordLabel = browser.describe(WebElement.class,new WebElementDescription.Builder().tagName("TD").innerText("Password:").build());

    		//Define the visual relation identifier of the username edit field.
    		VisualRelation usernameVRI = new VisualRelation();
    		usernameVRI.setTestObject(usernameLabel);
    		usernameVRI.setHorizontalRelation(HorizontalVisualRelation.LEFT_AND_INLINE);
    		browser.describe(EditField.class,new EditFieldDescription.Builder().vri(usernameVRI).build()).setValue("mercury");

    		///Enter the logon credentials using the labels.
    		VisualRelation passwordVRI = new VisualRelation();
    		passwordVRI.setTestObject(passwordLabel);
    		passwordVRI.setHorizontalRelation(HorizontalVisualRelation.LEFT_AND_INLINE);
    		browser.describe(EditField.class,new EditFieldDescription.Builder().vri(passwordVRI).build()).setSecure("55940fd62c96a30a62b4ab4d3db57c430de69cde");

    		//Click the Sign In button.
    		browser.describe(Image.class,new ImageDescription.Builder().alt("Sign-In").type(ImageType.BUTTON).tagName("INPUT").build()).click();

    		//Verify that a Sign out link is available.
    		Verify.isTrue(browser.describe(Link.class,new LinkDescription.Builder().tagName("A").innerText("SIGN-OFF").build()).exists(), "Verify_UserCanEnterCredentialsAfterSignOff", "Verify that the sign out link is available.");
    	}
    	catch (Error e)
    	{
    		Reporter.reportEvent("Verify_UserCanEnterCredentialsAfterSignOff", "Failed during test", Status.Failed, e);
    		throw e;
    	}
    	finally
    	{
    		browser.close();
    	}

    }

Back to top

## Verify objects using HTML attributes

This example will get all the images in the AUT's main page and verify that all images contains ALT attribute.

    @Test
    public void verify_AllImagesContainsAltAttribute() throws Exception
    {
    	//Launch the Chrome browser and navigate to the New Tours site.
    	Browser browser = BrowserFactory.launch(BrowserType.CHROME);
    	browser.navigate("http://newtours.demoaut.com/");
    	try
    	{
    		Image[] images = browser.findChildren(Image.class,null);
    		for (Image image : images)
    		{
    			Verify.isNotNullOrEmpty(image.getAttribute("alt"), "Verify_UserCanEnterCredentialsAfterSignOff", "Verify that each image is not null or empty.");
    		}
    	}
    	catch (Error e)
    	{
    		Reporter.reportEvent("Verify_UserCanEnterCredentialsAfterSignOff", "Failed during test", Status.Failed, e);
    		throw e;
    	}
    	finally
    	{
    		browser.close();
    	}

    }

Back to top

## 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();
    	}
    }

Back to top

## Open the Home page using browser controls

This example uses the Describe method to create a regular expression to locate an object.

    @Test
    public void verify_TipIsPresentedInAUTHomePage() throws Exception {
    	//Navigate to the home page of the browser using the browser's controls.

    	com.hp.lft.sdk.stdwin.EditField addressField = Desktop.describe(Window.class, new WindowDescription.Builder()
    	.ownedWindow(false).childWindow(false).windowClassRegExp("Afx:").windowTitleRegExp("JSCall").build()).describe(Window.class, new WindowDescription.Builder()
    	.ownedWindow(false).childWindow(true).windowClassRegExp("Afx:").windowTitleRegExp("http://localhost/t112.html").build()).describe(com.hp.lft.sdk.stdwin.EditField.class, new com.hp.lft.sdk.stdwin.EditFieldDescription.Builder()
    	.attachedText("URL:").nativeClass("Edit").build());

    	addressField.setText("http://newtours.demoaut.com/");
    	addressField.click();
    	addressField.sendKeys(Keys.RETURN);

    	//Describe the tip image. Since the tip index is generated we will use a regular expression to find it.
    	Image tip = Desktop.describe(Window.class, new WindowDescription.Builder()
    	.ownedWindow(false).childWindow(false).windowClassRegExp("Afx:").windowTitleRegExp("JSCall").build()).describe(Window.class, new WindowDescription.Builder()
    	.ownedWindow(false).childWindow(true).windowClassRegExp("Afx:").windowTitleRegExp("http://newtours.demoaut.com/").build()).describe(Page.class, new PageDescription()).describe(Image.class, new ImageDescription.Builder()
    	.alt(new RegExpProperty("Tip.*")).type(com.hp.lft.sdk.web.ImageType.NORMAL).tagName("IMG").build());

    	//Verifies that the tip is found.
    	Verify.isTrue(tip.exists(), "Verify_TipIsPresentedInAUTHomePage", "Verify that the tip field is found.");
    }

Back to top

## 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");
    }

Back to top

See also:

- Lean Functional Testing (LeanFT) Java SDK Reference
- LeanFT Java SDK code samples