Lately, I used to be going thru one of the design patterns in Java by way of studying the e-book Head First Design Patterns by way of Eric Freeman, Elisabeth Robson, Bert Bates, and Kathy Sierra.
It’s an ideal e-book with quite a lot of wisdom about a couple of design patterns in Java.
As I looked for examples to apply the design patterns I had not too long ago examine within the e-book, I got here throughout a development referred to as Fluent Interface. I discovered it fairly spectacular and considered growing an instance code to jot down internet automation exams the use of the fluent interface design development with Selenium WebDriver.
Here’s an instance of the code from one of the vital exams to turn you ways clean it’s to learn and perceive:
I suppose you may have an even concept of what this check does. It’ll navigate to the Website online’s Homepage, open the Registration Web page, and check its header.
Subsequent, it’s going to sign up the person, check whether or not registration is a hit, after which proceed to the My Account Web page.
The stairs for proceeding to the My Account Web page and checking its header needed to be integrated, as that marks the of entirety of the Registration procedure.
The purpose to notice here’s that no check information has been handed within the exams nor the process signature, making it glance blank and crisp!
Check information is handed internally whilst registering the person throughout the registerUser()
approach. Main points and explanations will observe on this instructional on Fluent Interface Design Patterns. Stay studying!
You spot how easy and funky it’s to jot down exams in a Fluent Method!
What Is a Fluent Interface Design Trend?
A fluent interface supplies an easy-readable, flowing interface that ceaselessly mimics a domain-specific language. The usage of this development ends up in code that may be learn just about as human language. A fluent interface can also be applied the use of any of the next:
- Approach chaining: calling one way returns some object on which additional strategies can also be referred to as.
- Static manufacturing facility strategies and imports.
- Named parameters: can also be simulated in Java the use of static manufacturing facility strategies.
A fluent interface design development is helping us write an easy-readable code that may be understood with out placing effort into technically working out the code.
The opposite get advantages is that it is helping in mimicking the domain-specific language, because of this we will be able to learn the code in trade language and perceive what it does.
As an example, take a look at the code snippet beneath, which is written the use of the fluent interface design development. That is how the fluent interface design development mimics domain-specific language.
homePage ().openUserRegistrationPage () .verifyPageHeader () .registerUser () .verifySuccessfulRegistration () .continueToMyAccount () .verifyPageHeader ();
Through studying the code, we get a greater working out in trade phrases that this piece of code will carry out person registration and take a look at whether it is a hit.
Getting Began With Fluent Interface Design Trend
Let’s get right into a deeper dialogue and evaluate about how you’ll be able to simply write exams in a fluent design interface development. Ahead of I start writing about how I wrote the exams and talk about the code, let me inform you concerning the gear and the web page below check.
Equipment Used
The next gear had been utilized in writing and working the exams:
- Programming Language: Java
- Internet Automation Software: Selenium WebDriver (newest edition)
- WebDriverManager is used for managing the drivers.
- Check Runner: TestNG
- Construct Software: Maven
Utility Underneath Check
LambdaTest E-Trade Playground Website online is used for writing the end-to-end exams on this weblog on fluent interface design patterns. This web page is used because it has a complete end-to-end demo trade go with the flow from registering a person to including and testing the product and confirming the order.
There are a couple of monitors having more than a few fields like textboxes, checkboxes, radio buttons, dropdown fields, and so forth., which can be utilized to demo just right examples of writing computerized exams the use of Selenium WebDriver.
It additionally provides beginners in automation checking out an even concept of acting end-to-end checking out and practising writing computerized exams the use of Selenium WebDriver. As it is a demo web page, someone can check out their palms in this web page and be informed automation checking out.
Check Technique for Automating Finish-To-Finish Float
Following is a check automation technique derived from checking out the end-to-end go with the flow of the web page:
- The Consumer will navigate to the web page.
- From the House Web page of the display screen, the person will navigate to the Registration Web page and sign up himself. Verification shall be performed by way of announcing the registration a hit message.
- Consumer will click on at the Store by way of Class choice at the best left and make a selection a class for settling on the product to buy.
- From the Product Web page, the person will hover over any product he likes and make a selection the Upload to cart choice. As soon as a product is added to the cart, assertions shall be carried out to test the good fortune message displayed.
- At the Checkout web page, the person will give you the billing deal with main points, and an statement shall be made for the product title and its respective worth.
- As soon as a product is looked at, the person lands at the Order Affirmation web page, the place the product title, worth, and delivery deal with shall be asserted, and after that Order shall be marked as showed.
- In spite of everything, an Order affirmation message could be verified within the exams, which marks the top of the check adventure.
GitHub Repository
The entire code showcased above is positioned on this GitHub Repository. Please take a look at the next programs within the discussed GitHub repository for exams, web page items, and check information for the code described on this weblog at the fluent interface design development:
Check: Checkoutsrctesttestslambdatestecommerce EndToEndWebsiteTests.java
Web page Gadgets: Checkout srctestpageslambdatestecommerce
bundle within the mission. Check Information: Checkout srctestdata
bundle within the mission.
How To Write Selenium Automation Exams The usage of the Fluent Interface Design Trend
As mentioned within the Tech Stack segment of this weblog at the fluent interface design patterns, Maven is used to create this mission. TestNG is used as a check runner. As soon as the mission is created, we want to upload the next dependencies for Selenium WebDriver, TestNG, WebDriverManager, JavaFaker, and Lombok within the pom.xml document.
<?xml edition="1.0" encoding="UTF-8"?>
<mission xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>io.github.mfaisalkhatri</groupId>
<artifactId>selenium4poc</artifactId>
<edition>1.0-SNAPSHOT</edition>
<title>selenium4poc</title>
<url>https://mfaisalkhatri.github.io</url>
<homes>
<mission.construct.sourceEncoding>UTF-8</mission.construct.sourceEncoding>
<selenium.java.edition>4.3.0</selenium.java.edition>
<testng.edition>7.6.1</testng.edition>
<webdrivermanager.edition>5.2.1</webdrivermanager.edition>
<javafaker.edition>1.0.2</javafaker.edition>
<lombok.edition>1.18.24</lombok.edition>
</homes>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<edition>${selenium.java.edition}</edition>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<edition>${testng.edition}</edition>
<scope>check</scope>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<edition>${webdrivermanager.edition}</edition>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.javafaker/javafaker -->
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<edition>${javafaker.edition}</edition>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<edition>${lombok.edition}</edition>
<scope>supplied</scope>
</dependency>
</dependencies>
<construct>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<edition>${maven.compiler.edition}</edition>
<configuration>
<liberate>${java.liberate.edition}</liberate>
<encoding>${maven.supply.encoding}</encoding>
<forceJavacCompilerUse>true</forceJavacCompilerUse>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<edition>${surefire-version}</edition>
<executions>
<execution>
<objectives>
<function>check</function>
</objectives>
</execution>
</executions>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
<homes>
<assets>
<title>usedefaultlisteners</title>
<price>false</price>
</assets>
</homes>
<suiteXmlFiles>
<suiteXmlFile>${suite-xml}</suiteXmlFile>
</suiteXmlFiles>
<argLine>${argLine}</argLine>
</configuration>
</plugin>
</plugins>
</construct>
</mission>
Variations of the dependencies are set in a separate homes block. That is performed for maintainability, so if we want to replace the variations, we will be able to do it simply with out looking the dependency all the way through the pom.xml document. Information about the dependencies:
- Selenium WebDriver: Core Selenium dependency for internet automation.
- TestNG: This dependency is helping to run the exams.
- WebDriverManager: This dependency carries out the driving force control, so that you don’t must obtain the drivers to run the exams in browsers manually.
- JavaFaker: This dependency is helping in producing pretend check information on run time.
- Lombok: This dependency is helping in mechanically producing Getters, Setters, and the use of the Builder development, so you’ll be able to eliminate writing long java categories and boilerplate code.
Finish-To-Finish Checking out With Fluent Interface Design Trend
Ahead of we commence and get started with the stairs used for writing the end-to-end exams in a Fluent means, some basic items want consideration so it lets you perceive higher. A mix of the next issues are used on this mission. I am hoping you will have a fundamental working out as a prerequisite:
- Web page Object Style is used for keeping up Web page Gadgets, and the fluent interface design development is used for writing exams.
- Builder Trend is used for pretend check information technology.
Let’s start with imposing the check automation technique mentioned previous on this weblog on fluent interface design patterns.
Check 1: Consumer Registration
To begin the exams, we want to navigate to the web page, open the registration web page, sign up the person, and carry out some assertions to test what we did was once proper. Here’s the primary check of this mission:
@Check
public void testRegisterUser () {
homePage ().openUserRegistrationPage ()
.verifyPageHeader ()
.registerUser ()
.verifySuccessfulRegistration ()
.continueToMyAccount ()
.verifyPageHeader ();
}
However sooner than we transfer directly to working out how the exams paintings, I suppose there could be a couple of questions that would seem on your thoughts, like what does the Website online appear to be, what does the Registration Web page appear to be, and what fields/locators are we operating on? So, to respond to the ones questions first, here’s what the Homepage of the LambdaTest ECommerce Playground seems like:
Here’s the screenshot of the Registration Web page, which opens after navigating to My Account >> Registration hyperlink from the above web page.
We want to first in finding the locators for the House Web page after which transfer directly to the Registration Web page.
personal WebElement registerLink () {
go back getDriver ().findElement (Through.linkText ("Sign in"));
}
personal WebElement selectCategory (ultimate String linkName) {
go back getDriver ().findElement (Through.linkText (linkName));
}
registerLink()
and selectCategory()
strategies are returning the WebElements
, which can be in reality locators for those respective fields.
personal HomePage openMyAccountMenu () {
getDriver ().findElement (Through.linkText ("My account"))
.click on ();
go back this;
}
openMyAccountMenu()
approach will find the component for My Account hyperlink and can click on on it.
openMyAccountMenu()
is part of the fluent interface design development and can go back the example of the House Web page magnificence. The wonderful thing about the “go back this
” observation is it’s going to permit acting approach chaining with all of the strategies within the HomePage magnificence.
public RegistrationPage openUserRegistrationPage () {
openMyAccountMenu ().registerLink ()
.click on ();
go back new RegistrationPage ();
}
openUserRegistrationPage()
will go back a brand new occasion of the Registration Web page magnificence as soon as the person clicks at the sign up hyperlink. This will likely permit chaining the strategies within the Registration Web page with this web page’s strategies.
public static HomePage homePage () {
go back new HomePage ();
}
Be aware: A static constructor has been created in each magnificence, so we don’t must instantiate the respective web page object categories and use static strategies by way of uploading it immediately within the check magnificence. Subsequent, we want to center of attention at the Registration Web page and maintain the method of registering the person. For registration, first, we want to in finding the locators of the Sign in person kind and give you the vital check information so it may be stuffed in mechanically when the check runs each time. Through doing this, we will be able to do away with manually converting the check information each time to generate a newly registered person.
We first want to take a look at if we now have landed on the right kind web page by way of checking the web page header to peer if it shows the textual content: “
Sign in Account
.”
public RegistrationPage verifyPageHeader () {
assertEquals (getDriver ().findElement (Through.tagName ("h1"))
.getText (), "Sign in Account");
go back this;
}
verifyPageHeader()
approach plays this take a look at by way of finding the component of the web page header after which checking it with the predicted textual content: “Sign in Account
” that we’ve got supplied for statement.
Realize the go back this
observation on the finish. This returns the example of the Registration Web page magnificence and is helping in chaining this system with different strategies of the Registration Web page Elegance.
personal WebElement registrationForm () {
go back getDriver ().findElement (Through.identity ("content material"));
}
personal WebElement firstNameField () {
go back registrationForm ().findElement (Through.identity ("input-firstname"));
}
personal WebElement lastNameField () {
go back registrationForm ().findElement (Through.identity ("input-lastname"));
}
personal WebElement emailField () {
go back registrationForm ().findElement (Through.identity ("input-email"));
}
personal WebElement telephoneField () {
go back registrationForm ().findElement (Through.identity ("input-telephone"));
}
personal WebElement passwordField () {
go back registrationForm ().findElement (Through.identity ("input-password"));
}
personal WebElement confirmPasswordField () {
go back registrationForm ().findElement (Through.identity ("input-confirm"));
}
personal WebElement emailField () {
go back registrationForm ().findElement (Through.identity ("input-email"));
}
personal WebElement agreePrivacyPolicyField () {
go back registrationForm ().findElement (Through.identity ("input-agree"));
}
personal WebElement continueBtn () {
go back registrationForm ().findElement
(Through.cssSelector("enter.btn-primary"));
}
There are a couple of fields that want to be stuffed in to sign up the person within the machine. firstNameField()
, lastNameField()
, emailField()
, telephoneField()
, passwordField()
, confirmPasswordField()
,and so forth. are obligatory fields required to be stuffed in to sign up a person.
So, the strategies returning the respective Selenium locators had been created within the RegistrationPage magnificence. Since these types of fields are to be had within the Registration Shape UI part, therefore registrationForm()
approach is created to find the registration kind as a mum or dad locator. The entire different fields, like the primary title, final title, e-mail, cellphone, password, and so forth., are positioned the use of the registrationForm()
approach because the mum or dad locator.
So, whilst discovering parts for the primary title box, Selenium WebDriver will seek for Registration Shape first, and within that part, it’s going to seek for the primary title box. This parent-child component discovering technique is helping in finding the weather sooner.
Ahead of we execute the registerUser()
approach, we want to have the knowledge to be had readily so it may be enter within the respective fields required for registering the person. For doing this, the RegisterUserData
magnificence is used. This magnificence has required variables which are obligatory for registering a person.
Realize the @Getter
and @Builder
annotations, which can be placed on best of the category title. Those are annotations supplied by way of Lombok.
@Getter
annotation will supply all of the getter strategies for the variables on run time.@Builder
annotation is helping us use the Builder Trend with out writing the boilerplate code.
Ahead of we continue against producing the Pretend check information for filling within the kind, let’s get some working out concerning the Builder Trend, as it’s going to assist in working out the method of faux check information technology simply.
What Is a Builder Trend?
Taking into consideration the above situation of registering a person the place we want to move a couple of parameters in a check, most often, what we do is create one way with that many parameters and use the POJO magnificence with the variables (fields required to sign up the person) to set the values within the check the use of the constructor of the POJO magnificence.
As an example, we should move first title, final title, e-mail, and password for registering customers. Now, we create a POJO magnificence, generate Getters and Setters within that magnificence, and set the values within the respective fields the use of a constructor. Checkout the code instance beneath for the illustration of what we’re discussing: POJO magnificence with variables required to sign up a person
public magnificence RegisterUser {
personal String e-mail;
personal String firstName;
personal String lastName;
personal String password;
public RegisterUser (ultimate String firstName, ultimate String lastName, ultimate
String e-mail, ultimate String password) {
this.firstName = firstName;
this.lastName = lastName;
this.e-mail = e-mail;
this.password = password;
}
public String getEmail () {
go back this.e-mail;
}
public String getFirstName () {
go back this.firstName;
}
public String getLastName () {
go back this.lastName;
}
public String getPassword () {
go back this.password;
}
public void setEmail (ultimate String e-mail) {
this.e-mail = e-mail;
}
public void setFirstName (ultimate String firstName) {
this.firstName = firstName;
}
public void setLastName (ultimate String lastName) {
this.lastName = lastName;
}
public void setPassword (ultimate String password) {
this.password = password;
}
}
Now, if we need to use this POJO, we must create an occasion of this magnificence and move the values within the parameters as given within the code instance beneath: The usage of the POJO magnificence in exams to move values.
@Check
public void testRegisterUser () {
ultimate RegisterUser registerUser = new RegisterUser ("John", "Doe", "john@abc.com", "Password123");
}
Consider if there are a couple of different fields additionally added within the registration kind, like deal with fields comparable to handle line one, line 2, line 3, town, state, nation, and so forth. We’d want to upload the ones variables within the POJO, and accordingly, the parameters within the constructor and, in spite of everything, within the exams will stay incrementing.
Because of the Builder Trend, this type of advanced downside can also be looked after out simply with out writing a couple of strains of code and making adjustments within the POJO categories over and over again.
Builder Trend is helping us remedy the problem of atmosphere the parameters by way of offering a solution to construct the items step-by-step by way of offering one way that returns the general object, which can be utilized in the true exams.
Let’s transfer again to the sign up Consumer Information magnificence, the place we mentioned the use of the Builder Trend. Lombok is helping us write quick and crisp code with no need to jot down boilerplate code. Through passing the @Getter
annotation, it mechanically generates Getters for the variables declared in RegisterUserData
magnificence. In a similar way, it generates the Builder development boilerplate code on run time by way of simply passing the @Builder
tag, relieving us from writing further code.
@Builder
@Getter
public magnificence RegisterUserData {
personal String e-mail;
personal String firstName;
personal String lastName;
personal String password;
personal String cellphone;
}
POJO is in a position subsequent we want to move at the information so it may be utilized in exams. We’d use the JavaFaker library
to generate the pretend information to move exams. TestDataBuilder
Elegance will maintain construction the knowledge for us.
getRegisterUserData()
approach will go back a suite of information required for the necessary fields for registering a person.
public RegistrationSuccessPage registerUser () {
enterText (firstNameField (), this.registerUserData.getFirstName ());
enterText (lastNameField (), this.registerUserData.getLastName ());
enterText (emailField (), this.registerUserData.getEmail ());
enterText (telephoneField (), this.registerUserData.getTelephone ());
enterText (passwordField (), PASSWORD);
enterText (confirmPasswordField (), PASSWORD);
ultimate Movements movements = new Movements (getDriver ());
movements.moveToElement (agreePrivacyPolicyField ())
.click on ()
.carry out ();
continueBtn ().click on ();
go back new RegistrationSuccessPage ();
}
When the registerUser()
approach is achieved, it’s going to invoke getRegisterUserData()
approach and generate the desired information on run time and assist in registering the person. As soon as the person is registered effectively, it’s going to go back a brand new occasion of the Registration Good fortune Web page, as that is the following web page that shall be displayed at the display screen as soon as registration is a hit.
verifySuccessfulRegistration()
approach will take a look at for the locator of the good fortune message, get its textual content, and can evaluate it with the predicted message “Your Account Has Been Created!” supplied within the approach. This statement shall be performed the use of the assertEquals()
approach supplied by way of TestNG.
public RegistrationSuccessPage verifySuccessfulRegistration () {
assertEquals (getDriver ().findElement (Through.tagName ("h1"))
.getText (), "Your Account Has Been Created!");
go back this;
}
After verification of a hit registration is finished, the continueToMyAccount()
approach is known as within the check, which can click on at the Proceed button and go back a brand new occasion of My Account Web page.
personal WebElement continueBtn () {
go back getDriver ().findElement (Through.cssSelector (".buttons >
a.btn-primary"));
}
public MyAccountPage continueToMyAccount () {
continueBtn ().click on ();
go back new MyAccountPage ();
}
At the My Account Web page we’re simply verifying that the web page header My Account is as it should be displayed.
To try this, the MyAccountPage magnificence is created, and inside it, the verifyPageHeader()
approach is created, which looks after the statement.
public magnificence MyAccountPage {
public MyAccountPage verifyPageHeader () {
assertEquals (getDriver ().findElement (Through.tagName ("h2"))
.getText (), "My Account");
go back this;
}
}
With this, our check for registering the person ends.
Now, it is sensible to learn the next code and perceive what it’s doing!
@Check
public void testRegisterUser () {
homePage ().openUserRegistrationPage ()
.verifyPageHeader ()
.registerUser ()
.verifySuccessfulRegistration ()
.continueToMyAccount ()
.verifyPageHeader ();
}
Check 2: Upload Product to Cart
Subsequent, we transfer on to test the second one trade situation by way of including a product to Cart. Here’s the check for it.
dependsOnMethods characteristic
Despite the fact that including a product to the cart is authorized as a visitor person as neatly when testing, the machine will ask the person to sign up to proceed, so it’s just right if we commence the check adventure as a registered person.
Under is the Screenshot of the Product Web page as it sounds as if at the LambdaTest ECommerce Playground web page:
House Web pageProduct Web page by way of clicking on Store by way of Class hyperlink PartsCheckout Product web page
public magnificence HomePage {
public static HomePage homePage () {
go back new HomePage ();
}
public ProductPage shopByCategory (ultimate String linkName) {
shopByCategory ().selectCategory (linkName)
.click on ();
go back new ProductPage ();
}
}
shopByCategory()
approach takes within the hyperlink title as a parameter, clicks on that respective hyperlink supplied, which, in our case is Parts, and returns a brand new occasion of the Product Web page magnificence.
Parameterization of the hyperlink title on this approach is finished, as within the case we want to click on on some other hyperlink, we will be able to supply that respective hyperlink title, and the similar code will paintings.
public ProductPage addPalmTreoCameraLensToCart () {
ultimate Movements movements = new Movements (getDriver ());
movements.moveToElement (palmTreoCameraLens ())
.pause (200)
.moveToElement (addToCartBtn ())
.pause (100)
.click on ()
.carry out ();
go back this;
}
We’d like to make a choice a product so as to add it to the cart, for this, we might be settling on the Palm Treo Digicam Lens and can upload it to the cart. This phase is a little difficult as the choice so as to add the product to the cart is displayed after soaring over the product.
Therefore, Selenium’s Movements magnificence has been used because it supplies the versatility to chain UI movements and is helping us do the similar guide motion the person could be doing in an automatic means.
The Movements magnificence of Selenium WebDriver lets in us to make use of the fluent interface design development by way of chaining strategies. The code snippet of the addPalmTreoCameraLensToCart()
approach supplied above is self-explanatory.
Be aware that this system will go back the example of the Product web page and assist us chain this system with different strategies of the Product Web page magnificence.
To ensure that the product is added effectively to the cart and ensure that the movements we did above are doing what they’re anticipated to do, we can check the good fortune message in the next move.
Be aware right here, MessageFormat
magnificence is used to structure the predicted message and make it glance extra readable and concise. In spite of everything, we can be transferring forward to take a look at the product subsequent.
public ProductPage verifySuccessMessage () {
ultimate String expectedMessage = "{0}n{1}n{2}n{3}n{4}";
assertEquals (notificationPopUp ().findElement (Through.tagName ("p"))
.getText (), MessageFormat.structure (expectedMessage, "Good fortune: You've added", "Palm Treo Professional", "on your",
"buying groceries cart", "!"));
go back this;
}
The checkoutProduct()
approach from Product Web page magnificence returns a brand new occasion of Checkout Web page magnificence after clicking at the Checkout Button displayed at the Good fortune Message on Product Web page.
personal WebElement checkoutBtn () {
go back notificationPopUp ().findElement (Through.cssSelector ("div.form-row > div:nth-child(2) > a"));
}
public CheckoutPage checkoutProduct () {
checkoutBtn ().click on ();
go back CheckoutPage.checkoutPage ();
}
This marks the of entirety of our check 2. Let’s now center of attention at the subsequent check to take a look at the product.
Check 3: Checkout Product
On this check, we can take a look at the Checkout Product web page and check its capability of testing the product.
Under is the screenshot of the web page showing at the LambdaTest ECommerce Playground web page.
That is the check that may assist us to make sure the product checkout capability.
Getting the Unit worth of Digicam Lens
unitPriceofCamerLens
Builder TrendJavaFaker
@Builder
@Getter
public magnificence BillingData {
personal String firstName;
personal String lastName;
personal String addressLineOne;
personal String town;
personal String postCode;
personal String nation;
personal String state;
}
For Billing Information, the necessary fields required to fill within the kind are:
- First Title
- Closing Title
- Deal with Line one
- Town
- Submit Code
- State
- Nation
We’ve got taken those fields into account, created a Billing Information magnificence, and added the annotations @Getter
and @Builder
, which can assist for the use of this magnificence with Builder Trend. The skeleton of the knowledge is created.
Let’s transfer directly to generate the check information, which shall be looked after within the Check Information Builder magnificence.
public magnificence TestDataBuilder {
personal static ultimate Faker FAKER = Faker.occasion ();
public static BillingData getBillingData () {
go back BillingData.builder ()
.firstName (FAKER.title ()
.firstName ())
.lastName (FAKER.title ()
.lastName ())
.addressLineOne (FAKER.deal with ()
.streetAddress ())
.town (FAKER.deal with ()
.cityName ())
.postCode (FAKER.deal with ()
.zipCode ())
.nation ("India")
.state ("Maharashtra")
.construct ();
}
}
getBillingData()
approach will go back a suite of information required for the necessary fields for atmosphere the Billing deal with required to be entered sooner than testing the product.
public CheckoutPage setBillingAddress (ultimate BillingData billingData) {
enterText (firstNameField (), billingData.getFirstName ());
enterText (lastNameField (), billingData.getLastName ());
enterText (addressLineOneField (), billingData.getAddressLineOne ());
enterText (cityField (), billingData.getCity ());
enterText (postCodeField (), billingData.getPostCode ());
countryField ().selectByVisibleText (billingData.getCountry ());
stateField ().selectByVisibleText (billingData.getState ());
go back this;
}
When the setBillingAddress()
approach is achieved it’s going to invoke getBillingData()
approach and generate all of the required information for atmosphere the billing deal with on run time.
public magnificence CheckoutPage { personal WebElement continueBtn () { go back this.wait.till (ExpectedConditions .elementToBeClickable (Through.cssSelector ("button#button-save"))); } personal WebElement agreeTermsAndConditionsField () { go back getDriver ().findElement (Through.cssSelector ("#input-agree +label")); } public ConfirmOrderPage checkoutProduct () { agreeTermsAndConditionsField ().click on (); continueBtn ().click on (); go back new ConfirmOrderPage (); } }
As soon as the billing deal with is ready, we might transfer forward to test the product by way of clicking at the agree phrases and stipulations checkbox after which in spite of everything clicking at the Proceed button to continue to the Order Affirmation web page.
Check 4: Ascertain Order Check
Now, it is time to verify the order we now have positioned the use of the former check. Under is the Ascertain Order web page screenshot as it sounds as if at the LambdaTest ECommerce Playground web page.
In this web page, we might be making some assertions and verifying that the product we decided on is handiest the only we’re testing, at the side of the cost we noticed within the preliminary level of including the product web page.
We can check the delivery deal with we added whilst testing the product.
This check will assist us check the Order Affirmation capability.
The verifyPageHeader()
approach has been created to claim the web page header to verify that we’re on the right kind web page sooner than we continue to run our subsequent steps of assertions. This system returns an occasion of the Ascertain Order Web page magnificence, so lets use it by way of chaining with different strategies of the Ascertain Order magnificence.
public ConfirmOrderPage verifyPageHeader () {
ultimate WebDriverWait wait = new WebDriverWait (getDriver (), Length.ofSeconds (10));
assertEquals (wait.till (ExpectedConditions.visibilityOfElementLocated (Through.tagName ("h1")))
.getText (), "Ascertain Order");
go back this;
}
The verifyProductName()
approach asserts the product title to test we’re ordering the right kind product. This system additionally returns the example of Ascertain Order Web page magnificence, so it might be clean to fluently use this system by way of chaining it with different strategies of the Ascertain Order Web page magnificence.
public ConfirmOrderPage verifyProductName () {
assertEquals (getDriver ().findElement (
Through.cssSelector ("#content material > div.table-responsive > desk > tbody > tr > td:nth-child(1)"))
.getText (), "Palm Treo Professional");
go back this;
}
Do you bear in mind we had stored the unit worth of the check magnificence by way of growing a world variable referred to as unitPriceOfCameraLens
within the check? We’d move that variable within the verifyUnitPrice()
approach parameter. This price shall be when compared with the worth we might be fetching for the product’s unit worth from the Order Ascertain web page.
public ConfirmOrderPage verifyUnitPrice (ultimate String unitPrice) {
assertEquals (getDriver ().findElement (
Through.cssSelector ("#content material > div.table-responsive > desk > tbody > tr > td:nth-child(4)"))
.getText (), unitPrice);
go back this;
}
Subsequent, we want to be sure that the Billing deal with we now have entered within the earlier step is as it should be displayed within the Delivery Deal with segment of the Order affirmation web page.
The verifyShippingAddress()
approach will assert the billing deal with. This system will take Billing Information
as a parameter, as we might be passing the similar occasion of billing information that we used for atmosphere the billing deal with. It is helping set and get the similar information and eases our job of saying the deal with.
public ConfirmOrderPage verifyShippingAddress (ultimate BillingData billingData){
ultimate String expectedMessage = "{0} {1}n{2}n{3} {4}n{5},{6}";
assertEquals (getDriver ().findElement (Through.cssSelector ("#content material > div.row > div:nth-child(2) > div > div"))
.getText (), MessageFormat.structure (expectedMessage,
billingData.getFirstName (), billingData.getLastName (),
billingData.getAddressLineOne (), billingData.getCity (),
billingData.getPostCode (),
billingData.getState (), billingData.getCountry ()));
go back this;
}
After the delivery deal with is verified, we can be transferring forward with confirming the order. confirmOrder()
approach will click on at the Ascertain Order button and assist us verify the order.
personal WebElement confirmOrderBtn () {
go back getDriver ().findElement (Through.identity ("button-confirm"));
}
public OrderSuccessPage confirmOrder () {
confirmOrderBtn ().click on ();
go back new OrderSuccessPage ();
}
This marks our verify order exams entire. Let’s transfer to checking if the order was once effectively marked as entire.
Check 5: Order Good fortune Check
We’ve got finished nearly our check adventure, with the final step ultimate, the place we want to take a look at if the order we positioned has been a hit.
Under is the Order Good fortune web page screenshot as it sounds as if at the LambdaTest ECommerce Playground web page.
On this check, we can check the good fortune message displayed at the Order Good fortune Web page after putting the order and confirming it.
public OrderSuccessPage verifySuccessMessage () {
ultimate WebDriverWait wait = new WebDriverWait (getDriver (), Length.ofSeconds (20));
wait.till (
ExpectedConditions.textToBePresentInElementLocated (Through.tagName ("h1"), "Your order has been positioned!"));
assertEquals (getDriver ().findElement (Through.tagName ("h1"))
.getText (), "Your order has been positioned!");
go back this;
}
verifySuccessMessage()
approach unearths the component of the good fortune message textual content at the web page and compares it with the predicted textual content “Your order has been positioned!” and returns the example of the Order Good fortune Web page magnificence so this system might be chained with different strategies of Order Good fortune Web page magnificence.
personal WebElement continueBtn () {
go back getDriver ().findElement (Through.cssSelector ("#content material > div > a"));
}
public void continueToHomePage () {
continueBtn ().click on ();
}
As soon as the verification of the good fortune message is finished, we can click on at the Proceed button, which can assist us navigate to the House Web page, marking the top of the end-to-end check adventure for the product acquire at the LambdaTest ECommerce Playground web page.
Working the Exams
There are two techniques to run the exams, and in each techniques, exams could be working at the LambdaTest cloud platform at the Chrome Browser. Cloud-based check infrastructure like LambdaTest supplies fast get entry to to an internet Selenium Grid of 3000+ actual browsers, gadgets, and working programs. Building and checking out groups can boost up their liberate cycle by way of working exams in parallel and slicing down check execution by way of a couple of folds.
- From the IDE the use of TestNG.
- From the CLI the use of Maven.
TestNG TestNG is used as a check runner. Therefore testng.xml has been created, the use of which we can run the exams by way of right-clicking at the document and settling on the choice Run ‘…testng.xml’. However sooner than working the exams, we want to upload the LambdaTest username and get entry to Key within the Run Configurations since we’re studying the username and accesskey from Device Assets. Upload Values within the Run Configuration as discussed beneath:
-Dusername = < LambdaTest username >
-DaccessKey = < LambdaTest get entry to key >
Here’s the Screenshot of the check run in the community the use of Intellij IDE.
Maven To run the exams the use of Maven, the next steps want to be run:
- Open command Recommended/Terminal.
- Navigate to the foundation folder of the mission.
- Kind the command:
mvn blank set up -Dusername=< LambdaTest username > -DaccessKey=< LambdaTest accessKey >
.
Following is the screenshot from IntelliJ, which presentations the execution standing of the exams the use of Maven:
Take a look at the Screenshots beneath, which gives you an even concept of the dashboard for computerized app exams.
The next Screenshots display the main points of the construct and the exams that had been run. Once more, the check title, browser title, browser edition, OS title, respective OS edition, and display screen answer are all as it should be visual for every check. It additionally has the video of the check that was once run, giving a greater concept about how exams had been run at the instrument.
This display screen presentations all of the metrics intimately, which may be very useful from the tester’s perspective to test what check was once run on which browser and, accordingly, additionally view the Selenium logs.
In the event you’re a tester or developer taking a look to support your Selenium Java abilities, the LambdaTest Selenium Java 101 certification permit you to advance your Selenium with Java abilities.
Conclusion
On this weblog at the fluent interface design development, we mentioned writing the Selenium internet automation exams in a fluent means. We used the LambdaTest Ecommerce Playground web page to run an end-to-end check adventure the place we registered a brand new person and handed the registration information the use of the builder development. Subsequent, we moved on so as to add a product to the cart, checkout, and in spite of everything verify the order and check that the order was once effectively positioned.
I am hoping you loved studying the weblog at the fluent interface design development and realized about Fluent and Builder patterns.
Glad Checking out!