Skip to content


Subversion checkout URL

You can clone with
Download ZIP
723 lines (558 sloc) 22.6 KB

What is FluentLenium ?

FluentLenium is a framework that helps you to write Selenium tests. FluentLenium provides you a fluent interface to the Selenium Web Driver. FluentLenium lets you use the assertion framework you like, either jUnit assertions, Hamcrest or AssertJ (old one: Fest-assert).

5 second example

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class BingTest extends FluentTest {
    public void title_of_bing_should_contain_search_query_name() {


To add FluentLenium to your project, just add the following dependency to your pom.xml:


By default, FluentLenium provides a jUnit adapter.

If you need the assertj dependency to improve the legibility of your test code:


An adapter has also been built for using FluentLenium with TestNG:


Just extend org.fluentlenium.adapter.FluentTestNg instead of org.fluentlenium.adapter.FluentTest.

Static imports

If you need to do some filtering:

import static org.fluentlenium.core.filter.FilterConstructor.*;

Static import using AssertJ

The static assertions to use AssertJ are:

import static org.assertj.core.api.Assertions.assertThat;
import static org.fluentlenium.assertj.FluentLeniumAssertions.assertThat;

Basic Methods

You can use url() , title() or pageSource() to get the url, the title or the page source of the current page.


Default Selector

You can use CSS1, CSS2 and CSS3 selectors with the same restrictions as in Selenium.

If you want to find the list of elements which have:

  • the id "title" : find("#title")
  • the class name "small" : find(".small")
  • the tag name "input" : find("input")

You are free to use most of the CSS3 syntax, which means that find("input[class=rightForm]") will return the list of all input elements which have the class rightForm

Custom filter

But what if you want all the input that have text equal to "Sam" ? You can use filters to allow that kind of search. For example:

find(".small", withName("foo"))
find(".small", withClass("foo"))
find(".small", withId("idOne"))
find(".small", withText("This field is mandatory."))

You can skip CSS selector argument: find(withId("idOne")) will return the element whose id attribute is "idOne".

You can also write chained filters: find(".small", withName("foo"), withId("id1")) will return all the elements matching the 3 criteria.

You can do more complex string matching on the above filters using the following methods:

  • contains
  • containsWord
  • notContains
  • startsWith
  • notStartsWith
  • endsWith
  • notEndsWith

For each of them, you can choose to use a css selector:

find(".small", withName().notContains("name"))
find(".small", withId().notStartsWith("id"))
find(".small", withText().endsWith("Female"))

Or to be more precise, you can use regular expressions:

find(".small", withName().contains(regex("na?me[0-9]*")))
find(".small", withName().notStartsWith(regex("na?me[0-9]*")))

Contains, startsWith and endsWith with a regexp pattern look for a subsection of the pattern.


If you want the first element that matches your criteria, just use:


or alternatively


If you want the element at the given position:

find(myCssSelector, 2)

Of course, you can use both position filter and custom filter:

find(myCssSelector, 2, withName("foo"))

Find on children

You can also chain the find call: find(myCssSelector).find("input") will return all the input elements in the css selector tree. You can be more specific:

find(myCssSelector, 2, withName("foo")).find("input", withName("bar"))


find(myCssSelector, 2, withName("foo")).findFirst("input", withName("bar"))


If you need to access to the name, the id, the value, the tagname or the text of an element:


If you need to access a specific value of an attribute:


You can also access a list of all the names, text, and ids of a list of elements:


If you want to know the name, the id, the value, the text or the value of an attribute of the first element on the list:


If you need to get the underlying html content of an element:


To know the dimension of an element (with and height):

Dimension dimension = findFirst(myCssSelector).getSize()

You can also check if the element is displayed, enabled or selected:


Form Actions

Clicking, filling, submitting and cleaning an element or list of elements is simple and intuitive.


fill("input").with("bar") or find("input").text("bar") will fill all the input elements with bar. If you want for example to exclude checkboxes, you can use the css filtering like fill("input:not([type='checkbox'])").with("tomato"), you can also use the filtering provided by FluentLenium fill("input", with("type", notContains("checkbox"))).with("tomato")

fill("input").with("myLogin","myPassword") will fill the first element of the input selection with myLogin, the second with myPassword. If there are more input elements found, the last value (myPassword) will be repeated for each subsequent element.

If you're trying to fill a select element, you can use fillSelect("daySelector").withValue("MONDAY") to fill it with a value, fillSelect("daySelector").withIndex(1) to fill it with a value by its index or fillSelect("daySelector").withText("Monday") to fill it with a value by its text.

Don't forget, only visible fields will be modified. It simulates a real person using a browser!



This will click on all the enabled fields returned by the search.



This will clear all the enabled fields returned by the search.



This will submit all the enabled fields returned by the search.

Double click


Page Object pattern

Selenium tests can easily become a mess. To avoid this, you can use the Page Object Pattern. Page Object Pattern will enclose all the plumbing relating to how pages interact with each other and how the user interacts with the page, which makes tests a lot easier to read and to maintain.

Try to construct your Page thinking that it is better if you offer services from your page rather than just the internals of the page. A Page Object can model the whole page or just a part of it.

To construct a Page, extend org.fluentlenium.core.FluentPage. In most cases, you have to define the url of the page by overriding the getUrl method. By doing this, you can then use the goTo(myPage) method in your test code.

It may be necessary to ensure that you are on the right page, not just at the url returned by getUrl [accessible in your test via the void url() method]. To do this, override the isAt method to run all the assertions necessary in order to ensure that you are on the right page. For example, if I choose that the title will be sufficient to know if I'm on the right page:

public void isAt() {

Create your own methods to easily fill out forms, go to another or whatever else may be needed in your test.

For example:

public class LoginPage extends FluentPage {
    public String getUrl() {
        return "myCustomUrl";
    public void isAt() {
    public void fillAndSubmitForm(String... paramsOrdered) {

And the corresponding test:

public void checkLoginFailed() {
    loginPage.fillAndSubmitLoginForm("login", "wrongPass");

Or if you have the AssertJ module (just static import org.fluentlenium.assertj.FluentLeniumAssertions.assertThat)

public void checkLoginFailed() {

Page usage

You can use the annotation @Page to construct your page easily.

For example:

public class AnnotationInitialization extends FluentTest {
    public WebDriver webDriver = new HtmlUnitDriver();

    public TestPage page;

    public void test_no_exception() {
        //put your assertions here

    public WebDriver getDefaultDriver() {
        return webDriver;


It's now possible to use the @Page annotation in a FluentPage.

You can also use the factory method createPage:

public class BeforeInitialization extends FluentTest {
    public WebDriver webDriver = new HtmlUnitDriver();
    public TestPage page;
    public void beforeTest() {
        page = createPage(TestPage.class);
    public void test_no_exception() {
    public WebDriver getDefaultDriver() {
        return webDriver;

Within a page, all FluentWebElement fields are automatically searched for by name or id. For example, if you declare a FluentWebElement named createButton, it will search the page for an element where id is createButton or name is createButton. All elements are proxified which means that the search is not done until you try to access the element.

public class LoginPage extends FluentPage {
   FluentWebElement createButton;
   public String getUrl() {
       return "myCustomUrl";
   public void isAt() {
   public void fillAndSubmitForm(String... paramsOrdered) {

Not only FluentWebElement fields are populated. Every type with a constructor taking a WebElement is a candidate. This makes it possible for the page to expose fields with functional methods and not (only) the 'technical' methods that FluentWebElement exposes.

public class LoginPage extends FluentPage {
   MyButton createButton;
   public void fillAndSubmitForm(String... paramsOrdered) {
   public static class MyButton {
       WebElement webElement;
       public MyButton(WebElement webElement) {
           this.webElement = webElement;
       public void clickTwice() {

If the naming conventions of your HTML ids and names don't match with the naming conventions of your Java fields, or if you want to select an element with something other than the id or name, you can annotate the field with the Selenium @FindBy (or @FindBys) annotation. The following example shows how to find the create button if its CSS class is create-button.

public class LoginPage extends FluentPage {
   @FindBy(css = "button.create-button")
   FluentWebElement createButton;
   public String getUrl() {
       return "myCustomUrl";
   public void isAt() {
   public void fillAndSubmitForm(String... paramsOrdered) {

If you need to wait for an element to be present, especially when waiting for an ajax call to complete, you can use the @AjaxElement annotation on the fields:

public class LoginPage extends FluentPage {
   FluentWebElement myAjaxElement;

You can set the timeout in seconds for the page to throw an error if not found with @AjaxElement(timeountOnSeconds=3) if you want to wait 3 seconds. By default, the timeout is set to one second.

Wait for an Ajax Call

There are multiple ways to make your driver wait for the result of an asynchronous call. FluentLenium provides a rich and fluent API in order to help you to handle AJAX calls. If you want to wait for at most 5 seconds until the number of elements corresponding to the until criteria (here the class small) has the requested size:

await().atMost(5, TimeUnit.SECONDS).until(".small").hasSize(3);

The default wait is 500 ms.

Instead of hasSize, you can also use hasText("myTextValue"), isPresent(), isNotPresent(), hasId("myId"), hasName("myName"), containsText("myName"),areDisplayed(), areEnabled(). The isPresent() assertion is going to check if there is at most one element on the page corresponding to the filter.

If you need to be more precise, you can also use filters in the search:

await().atMost(5, TimeUnit.SECONDS).until(".small").withText("myText").hasSize(3);

You can also use after hasSize() : 'greaterThan(int)', 'lessThan(int)', 'lessThanOrEqualTo(int)', 'greaterThanOrEqualTo(int)' , 'equalTo(int)', 'notEqualTo(int)'

You can also use matchers:

await().atMost(5, TimeUnit.SECONDS).until(".small").withText().startsWith("start").isPresent();

Just use startsWith, notStartsWith, endsWith, notEndsWith, contains, notContains, equalTo, containsWord.

If you need to filter on a custom attribute name, this syntax will help:

await().atMost(5, TimeUnit.SECONDS).until(".small").with("myAttribute").startsWith("myValue").isPresent();

You can also check if the page is loaded using

await().atMost(1, NANOSECONDS).untilPage().isLoaded();

If you want to wait until the page you want is the page that you are at, you can use:

await().atMost(5, TimeUnit.SECONDS).untilPage(myPage).isAt();

This methods actually calls myPage.isAt(). If the isAt() method of the myPage object does not throw any exception during the time specified, then the framework will consider that the page is the one wanted.

Polling Every

You can also define the polling frequency, for example, if you want to poll every 5 seconds:

await().pollingEvery(5, TimeUnit.SECONDS).until(".small").with("myAttribute").startsWith("myValue").isPresent();

The default value is 500ms.

You can also chain filter in the asynchronous API:

await().atMost(5, TimeUnit.SECONDS).until(".small").with("myAttribute").startsWith("myValue").with("a second attribute").equalTo("my@ndValue").isPresent();

Alternative Syntax

If you are more familiar with the JQuery syntax, you can use the familiar $ method:

assertThat(title()).isEqualTo("Hello toto");

Both syntax are equivalent. $ is simply an alias for the find method.

Execute javascript

If you need to execute some javascript, just call executeScript with your script as parameter. For example, if you have a javascript method called change and you want to call it just add this in your test:


You can either execute javascript with arguments, with async executeAsyncScript, and retrieve the result.

executeScript("change();", 12L).getStringResult();

Taking Snapshots

You can take a snaphost of the browser


The file will be named using the current timestamp. You can of course specify a path and a name using:


Isolate Tests

If you want to test concurrency or if you need for any reason to not use the mechanism of extension of FluentLenium, you can also, instead of extending FluentTest, instantiate your fluent test object directly.

= new IsolatedTest().goTo(DEFAULT_URL).
    await().atMost(1, SECONDS).until(".small").with("name").equalTo("name").isPresent().

Customize FluentLenium


If you need to change your driver, just override the getDefaultDriver method in your test. You can use every driver.

Base Url

If you want to defined a default base url, just override the getDefaultBaseUrl method in your test. Every pages create with @Page will also use this variable. If a base url is provided, the current url will be relative to that base url.


To set the time to wait when searching an element, you can use in your test:

withDefaultSearchWait(long l, TimeUnit timeUnit);

To set the time to wait when loading a page, you can use:

withDefaultPageWait(long l, TimeUnit timeUnit);

Be aware that when you modified this elements, the webDriver instance will be modified so your page will also be affected.


You can define a default driver configuration using two ways. First, just override the getDriver method and use the selenium way to configure your driver. You can also override the setDefaultConfig method and use both selenium and FluentLenium way (withDefaultSearchWait,withDefaultPageWait) to configure your driver.

Browser Lifecycle

For jUnit and testNG, you can define the browser lifecycle. Use the class annotation @SharedDriver and you will be able to define how the driver will be created:

@SharedDriver(type = SharedDriver.SharedType.ONCE)

will allow you to use the same driver for every test annotate with that annotation (it can also be on a parent class) for all classes and methods.

@SharedDriver(type = SharedDriver.SharedType.PER_CLASS)

will allow you to use the same driver for every test annotate with that annotation (it can also be on a parent class) for all methods on a same class.

@SharedDriver(type = SharedDriver.SharedType.PER_METHOD)

will allow you to create a new driver for each method.

The default is PER_METHOD.

You will also be able to decide if you want to clean the cookies between two methods using @SharedDriver(deleteCookies=true) or @SharedDriver(deleteCookies=false)


If you want to switch the Selenium webDriver to an iframe (see this Selenium FAQ), you can just call the method switchTo() :

To switch to the default context:




To switch to the iframe selected:



If you want manage alert (see this Selenium FAQ),

When an alert box pops up, click on "OK":


When an alert box pops up, click on "Cancel":


Entering an input value in prompt:



Maximize browser window:



If you have any comments/remarks/bugs, please raise an issue on github: FluentLenium or contact us through the mailing-list

FluentLenium and other frameworks


FluentLenium uses jUnit by default. You can use test using jUnit assertions, but can of course use others frameworks such as AssertJ or Hamcrest.

assertEqual("Hello toto",title());


Fest-Assert is now deprecated. This lib is no longer maintained. Consider switching to AssertJ


assertThat(title()).isEqualTo("Hello toto");
assertThat(find(myCssSelector)).hasText("present text");
assertThat(find(myCssSelector)).hasNotText("not present text");


assertThat(title(),equalTo("Hello toto"));


In English:

In French:

Please contact us on the mailing list if you want your post to be added to that list !

Built by CloudBees

Jump to Line
Something went wrong with that request. Please try again.