All posts by iamalittletester

Quick Tip: Selenium – select / deselect a value from a dropdown

The What

Having an HTML dropdown on a web page, i would like to select, via Selenium, an element from it, or deselect the selected one.

An example of an HTML representation of a dropdown can be found below – it displays a list of winter months:

<select id="winter">
 <option value="Dec">December</option>
 <option value="Jan">January</option>
 <option value="Feb">February</option>
 </select>

This element would look something like:

dropdown

The task is to easily select / deselect an element from the dropdwon.

The How

Continue reading Quick Tip: Selenium – select / deselect a value from a dropdown

A few developer principles that testers should follow

I’m thinking you should, in no particular order…

  1. Start from the basic . When learning a new language, start from the beginning. Understand the elementary notions of it. Make sure you know what the language represents, what it is used for, how to write it properly. Read the tutorials, try out the examples.
  2. Be lazy. Don’t reinvent the wheel. If you need some code that someone has already developed, use it. Use existing libraries where possible.
  3. Modularize, don’t copy paste. When you know you have bits of code that will repeat themselves, extract them in a separate method and call that method wherever the code is needed.
  4. Think and plan before you write your tests. Take time to analyze the requirements, to discuss the implementation with the developers, in order to identify the broadest and most relevant set of test cases. Take notes. Visualize how regular users will interact with the site. Make sketches. Jumping into testing just to finish it will make you skip some obvious scenarios.
  5. Name things properly. Whenever you pick a name for a method, attribute or test scenario, make it relevant to what it is supposed to do. Describe it as much as possible. Use a decent amount of letters (not 2-3 and not 100).
  6. Ask questions. Whenever something is not clear, or when you just need a confirmation of how well you understand the requirements, ask the people around you for information. No matter how basic or stupid the question might sound, it’s the start of a conversation which benefits all the people included in it.
  7. Separate concerns. Don’t put all the code in one class. Analyze what you must write. What part is the setup, what part is the verification? Usually tests should largely focus on the actual testing, not the setup, so maybe extract that part into a separate class/unit, so that you minimize how large a test it. Also, you can put in all validations in a separate place. In this case, when you read the test, you should have – a line of code which calls the setup; the test logic; one line of code that performs the validation (if possible).

Continue reading A few developer principles that testers should follow

Quick Tip: IntelliJ – easily updating method calls when method signature changes

The What

I wrote a Java method, whose signature contains a number of parameters. This method is called by many other methods (i use the method in my tests). After a while i realize one of the parameters is not needed anymore. I want to change the method signature and to update all its’ references throughout my code.

The How

Continue reading Quick Tip: IntelliJ – easily updating method calls when method signature changes

Selenium tests, the Object Oriented Way

Some while ago i published an article in a local magazine on the topic of writing Selenium tests in an Object Oriented fashion.  As i believe this is a very useful way of reducing the number of asserts tests can include, and to expand to a bigger audience, here is a different approach to writing Selenium tests.

This approach is recommended when you have, for example, a big module whose properties you must compare to the expected ones, after performing an action or when it comes to testing the translation of the page. Continue reading Selenium tests, the Object Oriented Way

Improving your code by using IntelliJ’s Inspections feature

Writing proper code in your IDE is made easier when using IntelliJ, due to its’ code analysis features. One option to perform a comprehensive coding issue search is to use the Inspect Code feature IntelliJ provides. From the class you want to check for issues, right click (inside the class, in the editor) and choose Analyze –> Inspect Code. Continue reading Improving your code by using IntelliJ’s Inspections feature

Page navigation with Selenium

While running tests with Selenium, you might want to navigate between the pages that are opening, without knowing or caring about the URL that is assigned to them. You would like to use the browser’s back and forward functionality, to just go back one page from the current one, or forward to the next page. You might also want to refresh the current page, without performing a driver.get(“someURL”). Continue reading Page navigation with Selenium

Working with cookies in Selenium

What are cookies

Cookies are text files stored on your computer, that contain information sites need to remember of your visit on them, like some of your preferences that the sites will persist while browsing their pages (for example: the language you are viewing the site in, the username you logged in with, the contents of your shopping cart, and so on). Cookies are used by your browser at the time you access the site. Each cookie has a name and a value, but also a scope, determined by the domain and path properties of the cookie (these are used to determine the site they belong to). A website can only set cookies valid on its’ domain and subdomains, not domains that do not belong to it. An expiry date can also be assigned to the cookie.
There are several types of cookies: session cookies are assigned to a website and are only valid while the site is being accessed. After leaving the site or closing the browser, these objects are deleted. Also, persistent cookies are used, those cookies that have an expiration date and that are valid beyond closing the browser.

Cookie objects supported by WebDriver

In the org.openqa.selenium module from the selenium-api library, you will find a class that emulates cookie objects, named of course, Cookie. A Cookie object can at most have the following attributes, as defined in this class: name; value; path; domain; expiry; isSecure. A Cookie object must have at least two attributes, namely name and value.
The Cookie object offers several constructors to build your cookie object, having the need to pass in the following parameters:

  • Minimal constructor with parameters: name, value. Example of creating such a Cookie object:
    Cookie cookie = new Cookie("testCookie", "testValue");
    
  • name, value, path
  • name, value, path, expiry
  • name, value, path, expiry, domain
  • name, value, path, expiry, domain, isSecure

Working with cookies in WebDriver

All methods related to cookies in WebDriver are accessible from the Options interface. First you must declare a variable for the webdriver, for example:

private WebDriver driver;

Then, you can use the cookie methods as described below:

  • Get all cookies: After opening a page whose cookies you want to find, use:
    driver.manage().getCookies();

    You can save these values in a set, to use them later on:

    Set<Cookie> cookies = driver.manage().getCookies();
  • Get a certain cookie: When you know the name of the cookie whose properties you want to get, you can use:
    driver.manage().getCookieNamed("cookieName");

    Storing the properties of this cookie is done by assigning the result of the above method to a Cookie object:

    Cookie theCookie = driver.manage().getCookieNamed("cookieName");
    
  • Deleting all the cookies on a page is done easily, by using:
    driver.manage().deleteAllCookies();
  • Deleting only a particular cookie, whose name you know, is done by using:
       driver.manage().deleteCookieNamed("cookieName");
  • Adding a new cookie: To add a new cookie to the browser, first you must create a Cookie object with all its’ needed properties. Afterwards, just use the following method:
    driver.manage().addCookie(cookieName);

    After adding the cookie, for it to be applied to the page you opened, a page refresh must be done right after adding it.

    Tip: In case you are not sure how to add the ‘domain’ property to a cookie, but you know what page it must be active on, you can: initially open that page; delete the cookie from the page, if it exists; create the Cookie object without setting the ‘domain’ property; add the cookie to the already opened page; refresh the page. The domain will be added automatically.

  • Editing cookies: You cannot directly edit the properties of a cookie. Instead, what you can do is: delete the existing cookie from the browser; create a new Cookie variable to reflect the new values you want for its’ properties ; add the new cookie to the browser; refresh the page.

DataProviders for TestNG tests

When you need to run the same test a number of times, by changing only a few variable values, instead of writing several identical tests, you can use the dataProvider functionality offered by TestNG. What you have to do is declare a dataProvider method that returns a list of lists of objects, pass it to the test method, change the test method’s signature to correspond to the types of objects found in each inner list and run the test. Continue reading DataProviders for TestNG tests

A few useful IntelliJ keyboard shortcuts

Although the list of shortcuts that IntelliJ offers is very large, here are just a few that make things so much easier when writing code (special thanks to the developers who pointed out some of them to me): Continue reading A few useful IntelliJ keyboard shortcuts

Useful: working with files and folders with FileUtils

When it comes to working with files (reading or writing their content, copying) or folders (copying their content, deleting them), the Apache FileUtils library offers a large number of methods for easily performing these tasks. Some of these are depicted below, together with their usage. For the full reference, check out this page: http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html.

Importing the library into the project you are working on has to be done by importing the latest org.apache.commons.io package, in which FileUtils is included. The latest version ca be found here: http://commons.apache.org/proper/commons-io/.

Below the most useful of these methods are presented, described, and their usage is exemplified.

Working with files
  • writing to files:
    • writeStringToFile(File file, String data): write the string ‘data’ into the file ‘file’, by overwriting any content within the file, if it exists. If the file does not exist, it is created at this step. Usage: writeStringToFile(new File(“pathToFiles/firstFile.txt”), “Some text with writeStringToFile that overwrites file”);
    • writeStringToFile(File file, String data, Charset encoding, boolean append): write the string ‘data’ into the ‘file’ file. The string copied uses the encoding specified as the parameter in the method. Also, the string will be copied at the end of the file if ‘append’ is true(it will be appended to the existing file content, nothing will be erased), or it will erase all the file’s content – if ‘append’ is false. If the file does not exist, it is created at this step. Usage: writeStringToFile(new File(“pathToFiles/firstFile.txt”), “\nSome text with encodȊng, appended and with spacing\n”, Charset.defaultCharset(), true);
    • writeLines(File file, Collection<?> lines, boolean append): write into the specified file ‘file’, the items from the ‘lines’ collection, by appending them to the existing content (if ‘append’ is true) or by overwriting the existing content (if ‘append’ is false). The default separator between the items of the collection will be the new line (each item of the collection will appear on a new line in the file). Usage (writing a list of strings into the file, appending them to the existing content):         writeLines(new File(“pathToFiles/firstFile.txt”), listOfStrings, true); where listOfStrings is, for example: List<String> listOfStrings = ImmutableList.of(“Element 1”, “Element 2”, “Element 3”);
    • writeLines(File file, Collection<?> lines, String lineEnding, boolean append): write into the specified file ‘file’, the items from the ‘lines’ collection, by appending them to the existing content (if ‘append’ is true) or by overwriting the existing content (if ‘append’ is false). The separator between each item will be the one specified by the string parameter ‘lineEnding’. Usage: writeLines(new File(“pathToFiles/firstFile.txt”), listOfStrings, “|”, true); where listOfStrings is, for example: List<String> listOfStrings = ImmutableList.of(“Element 1”, “Element 2”, “Element 3”);
  • reading from files:
    • readFileToString(File file): read all the content from the ‘file’, keeping the new line separators (the ‘\n’ ones). Usage: String fileToString = readFileToString(new File(“pathToFiles/copyFile.txt”)); – where the string ‘fileToString’ will be assigned all the content of the file.
    • readLines(File file): read all the content from the file and place each separate line into an element of a string list. Usage:         List<String> fileToListOfStrings = readLines(new File(“pathToFiles/copyFile.txt”));
  • comparing two files:
    • contentEquals(File file1, File file2): returns true if two files have the same size and content. Usage: assertTrue(contentEquals(new File(“pathToFiles/firstFile.txt”), new File(“pathToFiles/copyFile.txt”)));
Working with folders
  • copying stuff:
    • copyFile(File src, File destination): copy the content of the ‘src’ file into the ‘destination’ file. If the latter does not exist, it will be created at this step. Usage:         copyFile(new File(“pathToFiles/firstFile.txt”), new File(“pathToFiles/copyFile.txt”));  –> ‘copyFile.txt’ will have identical content to ‘firstFile.text’
    • copyDirectory(File srcDir, File destinationDir): copy all the content from folder ‘srcDir’ directly under ‘destinationDir’. Usage:         copyDirectory(new File(“pathToFiles/randomFolder”), new File(“pathToFiles/Test”)); –>’randomFolder’ and ‘Test’ folder will have identical structure and content
    • copyFileToDirectory(File file, File destinationDir): copy the file ‘file’ to the file with the same name from the ‘destinationDir’ folder. If it does not exist, create a new file with the same name and put the content inside it. Usage:        copyFileToDirectory(new File(“pathToFiles/firstFile.txt”), new File(“pathToFiles/thirdOne”)); –> the ‘thirdOne’ folder will hold a ‘firstFile.txt’ file whose content is identical to the file from the ‘pathToFiles/firstFile.txt’ path
    • copyDirectoryToDirectory(File srcDir, File destinationDir): copies the content from the ‘srcDir’ folder into the folder with the same name from the ‘destinationDir’ folder, if it exists. Otherwise it creates the folder with the same name, and then replicates the content into the new folder. Usage:         copyDirectoryToDirectory(new File(“pathToFiles/thirdOne”), new File(“pathToFiles/4thOne”));
  • deleting folders
    • deleteDirectory(File srcDir): delete the ‘srcDir’ and all its’ content. Usage:  deleteDirectory(new File(“pathToFiles/Test”));
Example
List listOfStrings = ImmutableList.of("Element 1", "Element 2", "Element 3");
//overwrite content of existing file
writeStringToFile(new File("pathToFiles/firstFile.txt"), "Some text with writeStringToFile that overwrites file");
//append string to existing content, with specified encoding
writeStringToFile(new File("pathToFiles/firstFile.txt"), "\nSome text with encodȊng, appended and with spacing\n", Charset.defaultCharset(), true);
//append a list of strings to the file, each string ends with a new line character; if append=false, boolean parameter can be removed
writeLines(new File("pathToFiles/firstFile.txt"), listOfStrings, true);
//append a list of strings to the file, each string ends with a specified character (| in this case) ; if append=false, boolean parameter can be removed
writeLines(new File("pathToFiles/firstFile.txt"), listOfStrings, "|", true);
//check that the content of two files is identical
copyFile(new File("pathToFiles/firstFile.txt"), new File("pathToFiles/copyFile.txt"));
assertTrue(contentEquals(new File("pathToFiles/firstFile.txt"), new File("pathToFiles/copyFile.txt")));
//copy a file to within a directory
copyFileToDirectory(new File("pathToFiles/firstFile.txt"), new File("pathToFiles/thirdOne"));
//copies a directory's content to another directory
copyDirectory(new File("pathToFiles/thirdOne"), new File("pathToFiles/4thOne"));
//copy directory into a directory with the same name, within the destination directory
copyDirectoryToDirectory(new File("pathToFiles/thirdOne"), new File("pathToFiles/4thOne"));
//read content from a file into a String
String fileToString = readFileToString(new File("pathToFiles/firstFile.txt"));
System.out.println("File to string: " + fileToString);
//read content from a file into a List of Strings
List fileToListOfStrings = readLines(new File("pathToFiles/firstFile.txt"));
System.out.println(fileToListOfStrings.size());
for (int i=0; i<=fileToListOfStrings.size()-1; i++)
System.out.println("The list of strings: " + fileToListOfStrings.get(i));

The resulting structure, in the ‘pathToFiles’ location, is: the ‘firstFile.text’ and ‘copyFile.txt’ files, alongisde the ‘thirdOne’ folder whose content is a ‘firstFile.txt’ file, and a ‘4thOne’ folder, comprising of a ‘firstFile.txt’ file and a ‘thirdOne’ folder (this folder also containing a ‘firstFile.txt’ file). The content of the all the .txt files is identical, as it was copied from one to the other.