Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

API Selenide: Developing Functional Tests in Java

See in this article how to work with Selenide API to develop functional testing of web applications.

Currently, WebDriver Selenium is one of the most popular tools for the development of functional tests of web application, once it is easy to use as well as very flexible. However, a web development team located in Estonia called Codeborne realized that when using Selenium WebDriver they would have to write the same code in the tests, for example, they had to initialize and close the browser each test and other unnecessary duplications. Thus, Codeborne team developed an API to remove the repetitive code, giving rise to Selenide.

First Steps with Selenide

Selenide is an API based on Selenium WebDriver for developing web functional tests in Java, offering a nice syntax for writing tests, easy to learn and use. The API solves all the typical problems like testing of modern web applications with Ajax and it abstracts for the developer the use of the WebDriver as well as Selenium configurations, and it also provides simple additional methods that Selenium, by "default", does not offer like: manipulate radiobutton , drop-down, screen capture and clear the browser cache.

In this article we will learn how to use Selenide and its main aspects.

Creating and configuring the project

To begin the development with Selenide we will use Eclipse, Maven and JUnit. To begin start Eclipse, then select "File> New> Other ..." and "Maven > Maven Project". Click "Next" and on the next screen select the checkbox "Create a simple project" and click "Next" again. In the window that appears, as in Figure 1, fill in the "Group Id" and "Artifact Id" fields and in "Packaging" select "war".

Figure 1. Eclipse window with the Maven project settings

After creating the project we need to make some adjustments: the first is to configure the pom.xml of our project adding the code in Listing 1 between the tags and into pom.xml.

Listing 1. File Code pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>project</groupId>
	<artifactId>learning-selenide</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies> 
		<!-- Selenide -->
		<dependency>
			<groupId>com.codeborne</groupId>
			<artifactId>selenide</artifactId>
			<version>2.23</version>
			<scope>test</scope>
		</dependency> 
		<!-- JUnit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies> 
	<!-- Build of this Maven project -->
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId> 
				<!-- Plugin compiler of Maven -->
				<version>3.3</version>
				<configuration> 
					<!-- Java version -->
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Finally, as our project is a web application, we need to generate a configuration file named "web.xml". For this select the maven project and double-click. Then click the right button under "Deployment Descriptor" and then click on "Generate Deployment Descriptor Stub". Select the project again and run the Maven Project Update using the Alt + F5 or right click choosing "Maven> Update Project" option. So our project is already configured.

Working with element's selectors

For the development of functional tests with Selenide we need to understand how the selection of elements (HTML) works, so we can carry out the test automation interacting with these elements in a web interface.

Selenide provides simple and useful commands to perform this task. Following are the commands similar to jQuery to select elements (HTML) with Selenide:

  • $(String seletorCss): Select an element (HTML) for its maked selector, eg, id. Thus, this command returns an SelenideElement object type with reference to a desired element;
  • $(By): Similar to the previous command, except in the way we pass the instruction to select the HTML element using a static method called "By".
  • $$(String seletorCss): Select an element (HTML) by its CSS selector, eg, id. This command returns a ElementsCollectionobject type with reference to various elements (HTML);
  • $$(By): Similar to the previous command, but the difference lies in the way we pass the instruction to select the element using a static method called "By".

To work together with the previous methods Selenide offersutilitiesmethods (static) that facilitate the selection of the elements:

  • byText: Search element (HTML) by text;
  • withText: Search element with certain specified text;
  • by: Search by element attribute;
  • byTitle: Search element by the attribute "title";
  • byValue: Search element by the attribute "value".

We will now have a practical example using the element selectors of Selenide. To do this, first select the directory "/src/main/webapp" and on it create a file called "selectors.html" adding the Listing 2 code in the same file that contains HTML elements that will be useful for our tests with Selenide selectors.

Listing 2.Code of the file selectors.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Working with element selectors</title>
</head>
<body>
	<div id="text">Get the element with the id: text</div>
	<a title="My title">Get the element with the title: My title</a>
	<form id="idForm">
		<input name="nameInput" type="text" value="Get the element with the value" />
	</form>
</body>
</html>

Then, we will create our test class that will test the elements of the previous listing. For this, select the directory "/src/test/java" and on it create a package called "test" and inside this create a class called "TestElementSelectors" adding the code in Listing 3.

Listing 3. Class Code of theTestElementSelectors.java

package test;
import static com.codeborne.selenide.Selectors.*;
import static com.codeborne.selenide.Selenide.*;
import static org.junit.Assert.assertEquals;
import org.junit.*; 
import org.openqa.selenium.By;

public class TestElementSelectors {

	@Before
	public void openThePageToTest() {
		open("http://localhost:8080/learning-selenide/selectors.html");
	}

	@Test
	public void testElementSelectorSelenide() {  
		assertEquals("<div id=\"text\">Get the element with the id: text</div>", $(By.id("text")).toString());
		assertEquals("<input name=\"nameInput\" type=\"text\" value=\"Get the element with the value\"></input>", $(By.name("nameInput")).toString());
		assertEquals("<div id=\"text\">Get the element with the id: text</div>", $("#text").toString());
		assertEquals("<div id=\"text\">Get the element with the id: text</div>", $(byText("Get the element with the id: text")).toString());
		assertEquals("<div id=\"text\">Get the element with the id: text</div>", $(withText("Get the element with the id: text")).toString());
		assertEquals("<div id=\"text\">Get the element with the id: text</div>", $(by("id", "text")).toString());
		assertEquals("<input name=\"nameInput\" type=\"text\" value=\"Get the element with the value\"></input>", $(by("value", "Get the element with the value")).toString());
		assertEquals("<a title=\"My title\">Get the element with the title: My title</a>", $(by("title", "My title")).toString());
		assertEquals("<a title=\"My title\">Get the element with the title: My title</a>", $(byTitle("My title")).toString());
		assertEquals("<input name=\"nameInput\" type=\"text\" value=\"Get the element with the value\"></input>", $(byValue("Get the element with the value")).toString());
	}

	@Test
	public void testSelectorElementsCollection() {
		assertEquals("<form id=\"idForm\"></form>", $(By.id("idForm")).toString());
		assertEquals("<form id=\"idForm\"></form>", $(by("id", "idForm")).toString());
	}
}

Note that our test class has two tests containing statements that will compare if the expected elements are equal to the elements in Listing 2 with the help of Selenide selectors. It is a simple example just to secure the use of selectors that we will use in concrete examples or real world later this article. To run our first test, we will have to publish our application before making it available for Selenide, making use of the Tomcat 8.

Once performed the deploy of the application we will now run our tests, for this, select the test class and then click the right mouse button by selecting the "Run As > JUnit Test" option. By default, Selenide will perform functional tests in the Firefox browser.

If all went as expected the result will look like Figure 2.

Figure 2. Results of tests with element selectors (HTML) of Selenide.

Working with SelenideElement

The SelenideElement interface is nothing more than a wrapper of Selenium WebDriver that Selenide improved bringing its API and now provides additional methods facilitating the work of test engineer in the development of automated functional testing. Following are some of the main additional methods of this interface:

  • should(Condition): Check if a particular element meets all the given conditions;
  • shouldNot(Condition): Checks whether a given element does not meet all the given conditions;
  • setValue(String): Sets a value in the value attribute of any HTML element;
  • val(): Gets the value of the value attribute of any HTML element;
  • pressEnter(): Press the ENTER;
  • isDisplayed(): Returns a boolean check if any element is visible;
  • exists(): Returns a boolean check if any element exists;
  • selectOptionByValue(String value): Select the option for the value of the element;
  • getSelectedOption(): Returns the selected option element;
  • getSelectedValue(): Returns the value of the selected option.

Now we'll do an example using the additional Selenide methods above. Just select the directory "/src/main/webapp" and on it create a file called "selenideElement.html" adding the Listing 4 code in this file that contains an HTML form that will be useful for our tests with additional methods of the Selenide.

Listing 4. File code of selenideElement.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Working with SelenideElement</title>
</head>
<body>
	<form id="form">
		<fieldset>
			<legend>Work with us</legend>
			
			<label for="input-1">Name:</label> 
			<input type="text" placeholder="Say your name" name="name" /> <br>
			
			<label>Gender:</label>
			<input type="radio" name="gender" value="Male">Male 
			<input type="radio" name="gender" value="Female">Female <br>
			
			<label>Language:</label> 
			<input type="checkbox" name="language" value="English">English 
			<input type="checkbox" name="language" value="Spanish">Spanish <br>
			
			<label>Position:</label>
			<select id="position">
				<option value="Developer">Developer</option>
				<option value="IT Manager">IT Manager</option>
				<option value="IT Support">IT Support</option>
			</select> <br> 
			
			<input type="submit" value="Send" id="btnSend" /> 
			<input type="submit" style="visibility: hidden;" value="Cancel" id="btnCancel" />
		</fieldset>
	</form>
</body>
</html>

Following we will create a class of tests that will test the elements of the previous listing. For this, select the directory "/src/test/java" and on it create a class called "TestSelenideElement" adding the Listing 5 code.

Listing 5. Class code of TestSelenideElement.java

package test;

import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selectors.by;
import static com.codeborne.selenide.Selenide.*;
import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;

public class TestSelenideElement {

	@Before
	public void openThePageToTest() {
		open("http://localhost:8080/learning-selenide/selenideElement.html");
	}

	@Test
	public void test() {
		$("#btnSend").should(visible);
		$("#btnCancel").shouldNot(visible);
		$(By.name("name")).setValue("John Cash");
		selectRadio(By.name("gender"), "Male");
		$(by("value", "English")).click();
		$(By.id("position")).selectOptionByValue("IT Support");
		assertEquals("John Cash", $(By.name("name")).val());
		assertEquals(true, $("#btnSend").exists());
		assertEquals(false, $("#btnCancel").isDisplayed());
		assertEquals("Male", getSelectedRadio(By.name("gender")).val());
		assertEquals("English", $(By.name("language")).val());
		assertEquals("IT Support", $(By.id("position")).getSelectedValue());
		$("#btnSend").pressEnter();
	}
}

Note that in the code we write a test that performs filling out a form and it verifies aspects of the fields using the additional Selenide methods. Once again published our web application in Listing 4 will run our tests. For this, select the test class "TestSelenideElement" and then click the right button by selecting the "Run As > JUnit Test" option.

If all went as expected the result will look like Figure 3.

Figure 3. Results of tests with the additional Selenide methods.

Working with conditions

Nowadays many web applications use AJAX to change parts of the site dynamically, so when we write functional tests with this purpose we need to define the waiting time until the desired item appears. For this, Selenide provides a class called Condition that, unlike Selenium WebDriver, Selenide waits for apre-settime limit.

By default, Selenide timeout is four seconds, but it can be configured via selenide.timeout property. Furthermore, Condition class is also used to test for checking a page state in which HTML elements are, for example, verify that input x is visible or not, and other checks. Here are some of the main attributes and methods of the Condition class:

  • visible | appear: A condition that indicates if the HTML element is visible on the web page;
  • present | exist: Condition that indicates if the HTML element exists on the web page;
  • hidden | disappear | not(visible): Condition that indicates if the HTML element is not visible on the web page;
  • readonly: Condition that indicates that the HTML element allow readonly on the web page;
  • attribute: A condition that indicates that some attribute is present in an HTML element;
  • name: Condition which indicates that the HTML element has a certain name value;
  • value: Condition which indicates that the HTML element has a certainamount of value;
  • type: Condition which indicates that the HTML element has a particular value type;
  • id: Condition which indicates that the HTML element hasa given id value;
  • empty: Condition indicating that the HTML element is empty;
  • cssClass: Condition which indicates that the HTML element has a certain class value;
  • focused: A condition that indicates if the HTML element is in focus;
  • enabled: A condition that indicates if the HTML element is enabled;
  • disabled: Condition that indicates if the HTML element is disabled;
  • selected: Condition that indicates if the HTML element is selected;
  • text: Condition that indicates if the HTML element has a certain value or text regardless of upper and lower case;
  • textCaseSensitive: Condition that indicates that the HTML element has a certain value or text considering uppercase and lowercase letters.

We will now have a practical example using the Condition class with their methods and attributes presented above. To do this, first select the directory "/src/main/webapp" and on it create a file called "condition.html" adding the Listing 6 code in this file which contains HTML elements that will be useful for our tests.

Listing 6. File code of condition.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Working with Conditions</title>
</head>
<body>
	<form id="myForm">
		<label for="name">Name:</label> 
		<input type="text" id="name" value="John" readonly="readonly" name="name"> <br /> 
		
		<label for="email">Email:</label>
		<input type="email" autofocus="autofocus" id="email">
	</form>


	<div class="footer_style" id="footer"></div>
	<p id="myParagraph">My text</p>
</body>
</html>

Then we will create our test class that will test the elements in Listing 6. To do this, select the directory "/src/test/java" and on it create a class called "TestCondition" adding the Listing 7 code.

Listing 7. Class code of TestCondition.java

package test;

import static com.codeborne.selenide.Condition.*;
import static com.codeborne.selenide.Selenide.*;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;

public class TestCondition {

	@Before
	public void openThePageToTest() {
		open("http://localhost:8080/learning-selenide/condition.html");
	}

	@Test
	public void testConditionForm() {
		$(By.id("myForm")).should(visible);
		$(By.id("myForm")).should(exist);
		$(By.id("myForm")).shouldNot(hidden);
		$(By.id("name")).should(readonly);
		$(By.id("name")).should(attribute("value"));
		$(By.id("name")).should(name("name"));
		$(By.id("name")).should(value("John"));
		$(By.id("name")).should(type("text"));
		$(By.id("name")).should(id("name"));
		$(By.id("footer")).should(empty);
		$(By.id("footer")).should(cssClass("footer_style"));
		$(By.id("email")).should(focused);
		$(By.id("email")).should(enabled);
		$(By.id("email")).shouldNot(disabled);
		$(By.id("myParagraph")).should(textCaseSensitive("My text"));
	}
}

Note that the code we write we have a test that will perform the check or checks in certain HTML elements using the Condition class of Selenide.

Watch a code snippet of Listing 7:

$(By.id("name")).should(name("name"));

We're doing a check on an HTML element that has the id="name" testing if it has a name attribute with the value "name": if so, the test passes, otherwise the test fails.

Be sure to make the deploy of the application with the new code as in Listing 6.

We will now run our test and for that select the test class "TestCondition". Then click with the right mouse button by selecting the "Run As > JUnit Test" option and if everything went as expected we will have the result like in Figure 4.

Figure 4. Results of tests with element selectors of Selenide.

Working with Collections of Elements

An HTML page consists of several elements, such as tables with multiple lines, multiple options for a selected element, radiobuttons groups, different types of lists, among others. So, for the development of functional tests we will need a construction that allows us to perform operations on multiple elements and Selenide provides useful ways to work with collections of elements, via ElementsCollection class. Following are the methods that this class has for us to work:

  • shouldBe: Checks what the HTML element has in a certain condition;
  • shouldhave: Check what the HTML element must have in a certain condition;
  • find: Search some information on the element;
  • filter: Filters some information on the element;
  • exclude: Filters all but certain elements of a condition.

In Listing 8 is an example where we use thepresented ElementsCollection classmethods. Just select the directory "/src/main/webapp" and on it create a file called "elementsCollection.html" adding the following code shown in this file that contains an HTML table useful for our tests.

Listing 8. File code of elementsCollection.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Working with Collections of Elements</title>
</head>
<body>
	<table border="1" id="tblMonthlyExpenses" style="width: 100%">
		<caption>Monthly Expenses</caption>
		<tr>
			<th>Month</th>
			<th>Expense ($)</th>
		</tr>
		<tr>
			<td>January</td>
			<td>$250</td>
		</tr>
		<tr>
			<td>February</td>
			<td>$500</td>
		</tr>
	</table>
</body>
</html>

Following we will create a test class that will test the elements of the previous listing. Just select the directory "/src/test/java" and on it create a class called "TestElementsCollection" adding the Listing 9 code.

Listing 9. Class code of TestElementsCollection.java

package test;

import static com.codeborne.selenide.CollectionCondition.size;
import static com.codeborne.selenide.Condition.text;
import static com.codeborne.selenide.Selenide.*;
import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

public class TestElementsCollection {

	@Before
	public void openThePageToTest() {
		open("http://localhost:8080/learning-selenide/elementsCollection.html");
	}

	@Test
	public void testTableMonthlyExpenses() {
		$("#tblMonthlyExpenses tr").shouldHave(size(3));
		assertEquals(true, $("#tblMonthlyExpenses tr td").findBy(text("$500")).exists());
		assertEquals(false, $("#tblMonthlyExpenses tr td").filterBy(text("January")).isEmpty());
		assertEquals(false, $("#tblMonthlyExpenses tr td").excludeWith(text("February")).isEmpty());
	}
}

Note that in the displayed class we write a test that will check some aspects of HTML elements of a table with the help of ElementsCollection class. Note the following code snippet taken from the previous listing:

$("#tblMonthlyExpenses tr").shouldHave(size(3));

With this code, we verify that the element "#tblMonthlyExpensestr" is the number of lines "tr" equal to three: if so the test passes, otherwise the test fails.

After performing the application to deploy the new code of Listing 8 we will run our tests. Just select the test class "TestElementsCollection" and then click the right button by selecting the "Run As > JUnit Test" option. If everything went as expected we will see the result equally to Figure 5.

Figure 5. Test result using the TestElementsCollection class

Conclusion

See that Selenide proved to be an excellent tool to automate functional tests in Java.

Thanks and see you all!



Fabrí­cio Galdino is a software expert and has worked with IT analysis and business development for more than five years. It has extensive experience with testing, back and front-end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login