"Turn" a few points to be concerned about selenium automated test cases (i)

Source: Internet
Author: User
Tags testng

Introduction to Automated test design Note: See article address

The information we provide in this chapter is useful for newcomers and experienced veterans in the field of automated testing. This article describes the most common types of automated tests and describes the "design patterns" that can enhance the maintainability and extensibility of your automated test suite. Experienced automated test engineers who have not yet used these technologies will be more interested in these technologies.

Test Type

What parts of the application should you test? This depends on the various factors that affect your project: User expectations, deadlines, priorities set by the project manager, and so on. However, once the project boundary definition is complete, as a test engineer, you must make decisions about what to test.

In order to classify the test types of Web applications, we have created some terminology here. These terms do not imply standards, but these concepts are typical for Web application testing.

Test static content

Static content testing is the simplest test for validating the existence of static, non-changing UI elements. For example:

→ each page has its intended page title? This can be used to verify that the link points to an expected page.

→ Does the app's home page contain a picture that should be at the top of the page?

→ Does each page of the site contain a footer area to show the company's contact details, privacy policy, and trademark information?

→ Does the title text of each page use the

You may or may not need to test the content of the page automatically. If your page content is not easily affected by manual content testing is sufficient. Content testing is valuable if, for example, the location of your application files is moved.

Test links

A common error for a Web site is that a broken link or link points to an invalid page. Link testing involves the point of each link and verifies that the intended page exists. If static links do not change frequently, manual testing is sufficient. However, if your web designer often changes the link, or if the file is redirected at a time, the link test should be automated.

Functional Testing

In your application, you need to test the specific functionality of your app, require some type of user input, and return some kind of result. Typically a functional test involves multiple pages, a form-based input page that contains several input fields, a commit and a cancel operation, and one or more response pages. User input can be entered via text input fields, check boxes, drop-down lists, or any other browser supported.

Functional testing is often the most complex type of test that requires automated testing, but is often the most important. Typical tests are logins, registered website accounts, user account operations, account settings changes, complex data retrieval operations, and more. Functional testing typically corresponds to your application's description of application features or design usage scenarios.

Testing dynamic elements

Typically a page element has a unique identifier that uniquely locates the elements in the page. Typically, a unique identifier is implemented with the ' id ' attribute or ' name ' property of the HTML tag. These identifiers can be static, constant, string constants. They can also be dynamic production values, which change on each page instance. For example, some Web servers may name the displayed file as doc3861 on one page instance, and display the doc6148 on other page strengths, depending on the ' document ' the user is retrieving. A test script that verifies the existence of a file may not be able to find the invariant identification code to locate the file. Typically, dynamic elements with variable identifiers exist on the results page based on user actions, however, obviously this depends on the Web application.

Here is an example.

<input id= "addform:_id74:_id75:0:_id79:0: CheckBox" type= "checkbox" value= "true"/>

This is a check box for HTML tags,

Its ID (addform:_id74:_id75:0:_id79:0:checkbox) is a dynamically generated value. The next time this page is opened, the ID of the check box may be a different value.

The Test of Ajax

Ajax is a technique that supports the dynamic change of user interface elements. Page elements can be changed dynamically, but do not require the browser to reload the page, such as animations, RSS feeds, other real-time data updates, and so on. Ajax has countless ways to update elements on a webpage. But the simplest way to understand Ajax is to think that in an AJAX-driven application, data can be retrieved from the application server and then displayed on the page without reloading the entire page. Only a small portion of the page, or only the element itself, is reloaded.

Validation results

Assert Assert and verify verify

When do I use the Assert command and when do I use the validation command? It depends on you. The difference is what you want the test program to do when the check fails. Do you want the test to terminate, or do you want to continue and simply record the check failure?

This requires a trade-off. If you use an assertion, the test stops when the check fails and does not run any subsequent checks. Sometimes, maybe it's often, that's what you want. If the test fails, you will immediately know that the test did not pass. Test engines such as testng and JUnit provide plug-ins that are commonly used when developing test scripts, and can easily mark tests that fail. Pros: You can simply see if the check is passed. Cons: When the check fails, subsequent checks are not executed and the result status of those checks cannot be collected.

In contrast, the validation command does not terminate the test. If your test uses only validation, you can be assured that it is-assuming there are no unexpected exceptions-the test will be executed, regardless of whether a defect is found. Cons: You have to do more work to check your test results. In other words, you won't get feedback from testng and JUnit. You will need to see the results in the print output console or in the log file. Each time you run the test, you will need to take the time to see the results output. If you're running hundreds of tests, each with its own log, this can be time consuming. It is more appropriate to get feedback in a timely manner, so assertions are often more commonly used than validation.

Trade-offs: Asserttextpresent,assertelementpresent and Asserttext

You should now familiarize yourself with these commands and the mechanics of using them. If not, please refer to the relevant section. When building your test, you need to decide

→ just check the text on the page? (verify/asserttextpresent)

→ Check only if HTML elements exist on the page? That is, text, images, or other content that is not checked, as long as it is related to HTML tags. (verify/assertelementpresent)

→ Need to examine both the element and its text content? (Verify/asserttext)

There's no right answer. This depends on your test requirements. If in doubt, use Asserttext, as this is the most stringent type checkpoint. You can change it later, but at least you won't miss out on any potential failures.

Verify/asserttext is the most specific type of test. Non-conformance of HTML elements (labels) or text causes the test to fail. Perhaps your web designer often changes the page surface, and you don't want your test to fail when they change the page because it's a recurring change in expectation. But if you still need to check things on the page, such as paragraphs, title text or images. In this case, you can use Verify/assertelementpresent. This ensures that a particular type of element exists (if you use XPath, you can ensure that it is relative to other objects within the page). But you don't care what the content is, you only care about a particular element, say, a picture in a particular location.

With the passage of time and the accumulation of experience, it is very easy to decide how to use it.

Strategies for locating elements

Select a targeting strategy

There are several ways to select objects on a page. But how do you weigh these types of positioning? Recall the way we positioned an object:

→ ID of the element

→ Element's Name property

→xpath statements

→ Text via a link

→ Document Object Model (DOM)

Using the ID of an element or the name locator is the most efficient way to test execution. Also make your test code more readable if the ID in the page source code or the Name property is friendly named. The XPath statement takes a longer time to process because the browser must run its XPath processor. 7,xpath in Internet Explorer is a slow name.

It's convenient to use the linked text for positioning, and it's good to run. This technique applies only to links. Also, if the link text is likely to change frequently, using the <a> tag to locate the element will be a better choice.

However, sometimes you have to use XPath targeting. If a page element does not have an ID or a name attribute, there is no choice except XPath positioning. (DOM locators are no longer commonly used because XPath can do better.) The DOM locator simply exists for legacy testing.

Using XPath for positioning has a unique advantage relative to using ID or Name property targeting. Using XPath (DOM), you can find an object on the page relative to other objects. For example, if you have a link that must exist within the second paragraph in the <div> tag, you can use XPath to locate it. Using the ID and Name property to locate, you can only conclude that they exist for the specified page, without knowing the specific page location. If you have to test that the image showing the company logo appears in the head section at the top of the page, XPath positioning may be a better choice.

Positioning dynamic Elements

As described in the previous Test Types section, the page identity of a dynamic element is different on the listing of different page instances. For example

<a class= "button" id= "Adminhomeform" onclick= "return Oamsubmitform (' Adminhomeform ', ' adminhomeform:_id38 ');" href = "#" >view archived Allocation events</a>

This HTML anchor tag defines an id attribute for the "adminhomeform" button. This is a fairly complex anchor tag compared to most HTML tags, but it is still a static label. Each time the page is loaded by the browser, the HTML remains unchanged. Its ID remains constant in all instances of the page, meaning that the UI element always has the same identifier when the page is displayed. So, the test script that clicks this button (Selenium Server) looks like this:

Selenium.click ("Adminhomeform");

However, your application may generate Dynamic HTML identifiers. In different instances of the page, the identifiers change. For example, an HTML element of a dynamic page might look like this:

<input id= "Addform:_id74:_id75:0:_id79:0:checkbox" type= "checkbox" Name= "addform:_id74:_id75:0:_id79:0: CheckBox "value=" true "/>

This is a check box, both the ID and the Name property are Addform:_id74:_id75:0:_id79:0:checkbox. In this case, using standard positioning, the test script should look like this:

Selenium.click ("Addform:_id74:_id75:0:_id79:0:checkbox");

For dynamically generated identifiers, this practice does not work. The next time the page loads, the identifier will be a different value, and executing the above script will encounter an "element not found" error.

A simple workaround to correct the problem is to use the XPath locator instead of the ID locator. Therefore, for this check box, you can simply use the

Selenium.click ("//input");

Or, if it is not the first text input field on the page, try a more detailed XPath statement.

Selenium.click ("//input[3]");

Or

Selenium.click ("//div/p[2]/input[3]");

However, if you do need to use an ID to locate an element, you can switch to a different solution. You can first capture the ID of the site and then use it, for example:

string[] Checkboxids = Selenium.getallfields (); Collect all input IDs on page.
for (String checkboxid:checkboxids) {
if (Checkboxid.contains ("AddForm")) {
Selenium.click (Expectedtext);
}
}

This method works if there is only one check box on the page with the ID text "Expectedtext".

Positioning AJAX Elements

The best way to locate and validate Ajax elements is to use the Selenium 2.0 Webdriver API, which specifically addresses some of the limitations of Selenium 1.0 testing AJAX elements.

In Selenim 2.0, you can use the WAITFOR () method to wait for a page element to become available. This parameter is a by object that Webdriver is used to implement positioning. This is explained in detail in the Webdriver chapter.

In Selenium 1.0 (SELENIUM-RC), to do this requires more coding, but it's not difficult. First check the element, if it exists, wait for a predefined period of time, and then recheck. This executes within the loop, and terminates the loop if the element does not exist if it exceeds a predetermined timeout.

Let's consider a link to the Ajax effect on the page (link = ajaxlink), which you can use for loop processing:

Loop initialization.
for (int second = 0;; second++) {

If loop is reached, seconds then break the loop.
if (second &gt;=) break;

Search for element ' Link=ajaxlink ' and if available then break loop.
try {if (selenium.iselementpresent ("Link=ajaxlink")) break;} catch (Exception e) {}

Pause for 1 second.
Thread.Sleep (1000);

}

This is certainly not the only solution. Ajax is a common topic, and in the user forums, look for previous discussions and see how others do it.

Encapsulating Selenium Calls

As with any programming, you need to use tool functions to handle the functions that are duplicated in the test code. One way to avoid duplication is to encapsulate calls to commonly used selenium methods. For example, when testing, you often click on the elements on the page and wait for the page to load.

Selenium.click (Elementlocator);
Selenium.waitforpagetoload (Waitperiod);

In order not to repeat the above code, you can write a wrapper method to implement these two functions.

/**
* Clicks and Waits for page to load.
*
* param Elementlocator
* param Waitperiod
*/
public void Clickandwait (string elementlocator, String waitperiod) {
Selenium.click (Elementlocator);
Selenium.waitforpagetoload (Waitperiod);
}

"Safe operation" to determine the existence of an element

Another common way to encapsulate selenium is to check the existence of elements on the page before performing further operations. This is sometimes referred to as a "safe operation." For example, the following method can be used to implement a security action that relies on the desired element.

/**
* SELENUM-RC--Clicks on element if the it is available on page.
*
* param Elementlocator
*/
public void Safeclick (String elementlocator) {
if (Selenium.iselementpresent (Elementlocator)) {
Selenium.click (Elementlocator);
} else {
Using the TestNG API for logging
Reporter.log ("Element:" +elementlocator+ ", is isn't available on page-"
+selenium.getlocation ());
}
}

The above example uses Selenium 1.0 Api,selenium 2.0, which also supports safe operation.

/**
* Selenium-webdriver--Clicks on element if the it is available on page.
*
* param Elementlocator
*/
public void Safeclick (String elementlocator) {
Webelement webelement = Getdriver (). Findelement (By.xxxx (elementlocator));
if (webelement! = null) {
Selenium.click (Elementlocator);
} else {
Using the TestNG API for logging
Reporter.log ("Element:" +elementlocator+ ", is isn't available on page-"
+ Getdriver (). GETURL ());
}
}

In the second example, the ' XXXX ' method is a placeholder that can be replaced with an element-positioning method.

The use of security methods depends on the decision of the test developer. Therefore, if the test needs to continue, even if you know that some elements on the page are not found, you can use a security method and send a message with missing elements to the log file. This is basically equivalent to implementing a validation with a reporting mechanism, rather than an assertion that terminates execution with a failure. However, if the element must appear on the page so that it can perform further actions, such as a login button on the home page of a portal site, the security method technology should not be used.

"Turn" a few points to be concerned about selenium automated test cases (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.