Вы находитесь на странице: 1из 7

Selenium RC for Java- Documentation

What is Selenium? Selenium is a testing tool for web applications that uses JavaScript to run tests directly in a browser. There are several test tools based on this technology such as Selenium IDE and Selenium Remote Control. The Selenium-IDE (Integrated Development Environment) is the tool you use to develop your Selenium test cases. Its an easy-to-use Firefox plug-in and is generally the most efficient way to develop test cases. It also contains a context menu that allows you to first select a UI element from the browsers currently displayed page and then select from a list of Selenium commands with parameters pre-defined according to the context of the selected UI element. This is not only a time-saver, but also an excellent way of learning Selenium script syntax. What is Selenium Remote Control? Selenium-RC is the solution for tests that need more than simple browser actions and linear execution. Selenium-RC uses the full power of programming languages to create more complex tests like reading and writing files, querying a database, emailing test results. Youll want to use Selenium-RC whenever your test requires logic not supported by Selenium-IDE. For example, Selenium-IDE does not directly support: condition statements iteration logging and reporting of test results error handling, particularly unexpected errors database testing test case grouping re-execution of failed tests test case dependency screenshot capture of test failures

Although these tasks are not supported by Selenium directly, all of them can be achieved by using programming techniques with a language-specific Selenium-RC client library. Installation After downloading the Selenium-RC zip file, install the Selenium-RC Server. The Selenium-RC server is simply a Java jar file (selenium-server.jar), which doesnt require any special installation. Just downloading the zip file and extracting the server in the desired directory is sufficient. Similarly, extract the file selenium-java-client-driver.jar.

Add to your project classpath the files selenium-server.jar and selenium-java-clientdriver.jar. Running Selenium Server Before starting any tests you must start the server. Go to the directory where SeleniumRCs server is located and run the following from a command-line console. java -jar selenium-server.jar For the server to run, youll need Java installed and the PATH environment variable correctly configured to run it from the console. Programming Your Test Now, we will know how to program a test using java as a supported programming language by adopting a test engine platform like TestNG. The TestNG framework is used to organize different tests and to report results. The basic structure that one has to follow to create a test case is: 1. Write a test case in Java using Selenium commands or record a test case using Selenium IDE (Firefox browser only) and export the test case into Java. 2. Edit the test case java file, and add TestNG annotations: i. Open the java test file you just created in an editor ii. Add the following: (a) To the import statements (along with import com.thoughtworks.selenium.*;): import org.testng.annotations.*; import org.testng.Assert; (b) To variable declarations: private Selenium selenium; private static String TIMEOUT_PERIOD ="10000"; (c) To the class: @BeforeClass(alwaysRun = true) public void setUp() { selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://10.232.172.66:9090"); selenium.start(); }

An explanation of the variables in the DefaultSelenium constructor: seleniumServerHost is the where the Selenium Server is running. Typically, it is localhost. seleniumServerPort is the port on which the Selenium Server is listening. The default is 4444. browserType is the type of browser you want to use for testing. Common browser types are *firefox, *iexplore, *opera. baseURL is the base URL for the site you are testing. The Selenium object created is tied to that particular URL and can only be used for that URL. @AfterClass(alwaysRun = true) private void stopTest() { selenium.stop(); } (d) After each statement in the test that will take time for a page to load: selenium.waitForPageToLoad(TIMEOUT_PERIOD); (e) On top of the test method: @Test(groups = { "<your test group name>" }) e.g. @Test(groups = { "default" }) (f) Edit page to be opened. Make sure argument to open method of selenium points to the right context root e.g. If http://10.232.172.66:9090/embsascare/login.do is the correct URL to test, then since we already have tried to open http://10.232.172.66:9090 in setup(), we only need to open the context root page. selenium.open("/embsascare/login.do"); Your java test case should look something like this after adding the TestNG annotations: import com.thoughtworks.selenium.*; import java.util.regex.Pattern; import org.testng.Assert; import org.testng.annotations.*; public class ManageRoles { private Selenium selenium; private static String TIMEOUT_PERIOD ="30000"; @BeforeClass(alwaysRun=true)

public void setUp() { selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://10.232.172.66:9090"); selenium.start(); } @Test (groups = {"default"}) public void testForm() { selenium.open("/embsascare/login.do"); selenium.waitForPageToLoad(TIMEOUT_PERIOD); selenium.type("j_username", "XXXX"); selenium.type("j_password", "YYYYY"); selenium.click("Login"); selenium.waitForPageToLoad(TIMEOUT_PERIOD); selenium.click("link=Manage Roles"); selenium.waitForPageToLoad(TIMEOUT_PERIOD); selenium.click("//input[@onclick='toggleCheckBoxes(this,3,2)']"); selenium.click("//input[@onclick='toggleCheckBoxes(this,4,2)']"); selenium.click("//*[@class=\"x-btn-text save\"]"); selenium.click("link=Logout"); } @AfterClass(alwaysRun=true) public void stopTest() { selenium.stop(); } } iii. Save the test file (a). Update testng.xml file. TestNG uses this file to read which groups to execute and also to pass parameters to the test. Make sure the class name is updated correctly. Here is an example testng.xml file: <!DOCTYPE suite SYSTEM http://testng.org/testng-1.0.dtd > <suite name="Care_TestCases" verbose="4"> <test name="DefaultTest"> <groups> <run> <include name="default" /> </run> </groups> <classes> <class name="ManageRoles"/> </classes> </test> </suite>

iv. Ensure that the java test file you created is compiled. 3. Execute the test case from command line using TestNG. Make sure the selenium server is started before running the tests. Assuming that you have TestNG in your class path, the simplest way to invoke TestNG from the command line is as follows: java org.testng.TestNG testng.xml On execution, you should see a new IE browser window open up, and run through your test. Retrieving and Reporting Results Each programming language has its own testing framework which is used to run the tests. If Selenium Test cases are developed using TestNG then no external task is required to generate test reports. The TestNG framework generates an HTML report which list details of tests. Check reports generated by TestNG under test-output directory. Open the index.html to see different output from the test. Some interactions In order to test a system, we need to be able to interact with it and make assertions about it. When the system we wish to test is a web application UI, we need to be able to interact with the page/browser and making assertions about the same. Lets look at how we can this with Selenium Remote Control. The most common interactions are accomplished through the following methods in DefaultSelenium:

open(String url) click(String locator) type(String locator, String value) select(String locator, String optionLocator) check(String locator) waitForPageToLoad(String timeoutInMilliseconds)

Now that we have a way of interacting, we need to be able to get information about a page. DefaultSelenium has many methods for getting information about a page:

getTitle() getText(String locator) getValue(String locator) isEditable(String locator) isElementPresent(String locator)

getSelectedLabel(String locator) getSelectedValue(String locator) isSomethingSelected(String locator) isChecked(String locator) getAlert()

Executing java script Java script comes very handy in exercising application which is not directly supported by selenium. getEval method of selenium API can be used to execute java script from selenium RC. Consider an EXT JS application having check boxes with no static identifiers. In this case one could evaluate js from selenium RC to get ids of all check boxes and then exercise them as given below: public static String[] getAllCheckboxIds () { String script = "var inputId = new Array();";// Create array in java script. script += "var cnt = 0;"; // Counter for check box ids. script += "var inputFields = new Array();"; // Create array in java script. script += "inputFields = window.document.getElementsByTagName('input');"; // Collect input elements. script += "for(var i=0; i<inputFields.length; i++) {"; // Loop through the collected elements. script += "if(inputFields[i].id !=null " + "&& inputFields[i].id !='undefined' " + "&& inputFields[i].getAttribute('type') == 'checkbox') {"; // If input field is of type check box and input id is not null. script += "inputId[cnt]=inputFields[i].id ;" + // Save check box id to inputId array. "cnt++;" + // increment the counter. "}" + // end of if. "}"; // end of for. script += "inputId.toString();" ;// Convert array in to string. String[] checkboxIds = selenium.getEval(script).split(","); // Split the string. return checkboxIds; } XPath : Finding GUI element Identifying an EXT JS framework based button can be difficult as there can be no static identifiers. For example, an AJAX based button having the below XPath: //a[@id,'ccd_ccd_81533739_removeevent'] Attribute(@id) value has both constant and dynamic texts which makes it difficult to uniquely identify the element based on its value. There is a numeral "81533739" which is not constant and it changes every time but the first part (ccd_ccd_) and the second part

(_removeevent) of the @id value is constant. In order to uniquely identify @id attribute based on these constant text alone, the below xpath using concat() and contains() should work fine: //a[contains(@id,concat("ccd","_","ccd","_")) and contains(@id,"removeevent")] Conclusion With Selenium and TestNG, we can easily test web UIs. The examples here are basic, but they demonstrate how just a few basic Selenium commands can get you most of what you need to test the UI.

Вам также может понравиться