• Stars
    star
    397
  • Rank 108,561 (Top 3 %)
  • Language
    Java
  • License
    MIT License
  • Created over 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Ready to use Lean Test Automation Architecture using Java and Selenium WebDriver to speed up your test automation

Lean Test Automation Architecture using Java and Selenium WebDriver

Actions Status

This project delivers to you a complete lean test architecture for your web tests using the best frameworks and practices.

It has a complete solution to run tests in different ways:

  • local testing using the browser on your local machine
  • parallel (or single) testing using Selenium Docker
  • local testing using TestContainers
  • Distributed execution using Selenium Grid

Important information

Know issues

This current version has excluded the guava library from WebDriverManager and Allure Environment Writer 
due to a conflict with the guava version of Selenium 4

Examples

Local testing execution example

Local testing execution example

Parallel testing execution example with Selenium Grid

Parallel testing execution example with Selenium Grid

Languages and Frameworks

This project uses the following languages and frameworks:

Test architecture

We know that any automation project starts with a good test architecture.

This project can be your initial test architecture for a faster start. You will see the following items in this architecture:

Do you have any other items to add to this test architecture? Please do a pull request or open an issue to discuss.

Page Objects pattern

I will not explain the Page Object pattern because you can find a lot of good explanations and examples on the internet. Instead, I will explain what exactly about page objects I'm using in this project.

AbstractPageObject

This class has a protected constructor to remove the necessity to init the elements using the Page Factory. Also, it sets the timeout from the timeout property value located on general.properties file.

All the Page Object classes should extend the AbstractPageObject. It also tries to remove the driver object from the Page Object class as much as possible.

Important information

There's a NavigationPage on the common package inside the Page Objects. Notice that all the pages extend this one instead of the AbstractPageObject. I implemented this way:

  • because the previous and next buttons are fixed on the page (there's no refresh on the page)
  • to avoid creating or passing the new reference to the NavigationPage when we need to hit previous or next buttons

As much as possible avoid this strategy to not get an ElementNotFoundException or StaleElementReferenceException. Use this approach if you know that the page does not refresh.

Execution types

There are different execution types:

  • local
  • local-suite
  • selenium-grid
  • testcontainers

The TargetFactory class will resolve the target execution based on the target property value located on general.properties file. Its usage is placed on the BaseWeb class before each test execution.

Local execution

Local machine

This approach is automatically used when you run the test class in your IDE.

This execution type uses WebDriverManager class to instantiate the web browsers. When the target is local the createLocalDriver() method is used from the BrowserFactory class to return the browser instance.

The browser used in the test is placed on the browser property in the general.properties file.

Local Suite

This execution type also uses the WebDriverManager to instantiate the web browser. The difference is that the browser is taken from the TestNG suite file instead of the general.properties file, enabling you to run multi-browser test approach locally.

Testcontainers

This execution type uses the WebDriver Containers in Testcontainers to run the tests in your machine, but using the Selenium docker images for Chrome or Firefox.

When the target is testcontainers the TargetFactory uses the createTestContainersInstance() method to initialize the container based on the browser set in the browser property. Currently, Testcontainers only supports Chrome and Firefox.

Example

 mvn test -Pweb-execution -Dtarget=testcontainers -Dbrowser=chrome

Remote execution

Selenium Grid

The Selenium Grid approach executes the tests in remote machines (local or remote/cloud grid). When the target is selenium-grid the getOptions method is used from the BrowserFactory to return the browser option class as the remote execution needs the browser capability.

The DriverFactory class has an internal method createRemoteInstance to return a RemoteWebDriver instance based on the browser capability.

You must pay attention to the two required information regarding the remote execution: the grid.url and grid.port property values on the grid.properties file. You must update these values before the start.

If you are using the docker-compose.yml file to start the Docker Selenium grid, the values on the grid.properties file should work.

You can take a look at the Execution with Docker Selenium Distributed to run the parallel tests using this example.

BrowserFactory class

This Factory class is a Java enum that has all implemented browsers to use during the test execution. Each browser is an enum, and each enum implements four methods:

  • createLocalDriver(): creates the browser instance for the local execution. The browser driver is automatically managed by the WebDriverManager library
  • createDriver(): creates the browser instance for the remote execution
  • getOptions(): creates a new browser Options setting some specific configurations, and it's used for the remote executions using the Selenium Grid
  • createTestContainerDriver() : Creates selenium grid lightweight test container in Standalone mode with Chrome/Firefox/Edge browser support.

You can see that the createLocalDriver() method use the getOptions() to get specific browser configurations, as starting the browser maximized and others.

The getOptions() is also used for the remote execution as it is a subclass of the AbstractDriverOptions and can be automatically accepted as either a Capabilities or MutableCapabilities class, which is required by the RemoteWebDriver class.

DriverManager class

The class DriverManager create a ThreadLocal for the WebDriver instance, to make sure there's no conflict when we run it in parallel.

BaseTest

This testing pattern was implemented on the BaseWeb class to automatically run the pre (setup) and post (teardown) conditions.

The pre-condition uses @BeforeMethod from TestNG creates the browser instance based on the values passed either local or remote execution. The post-condition uses @AfterMethod to close the browser instance. Both have the alwaysRun parameter as true to force the run on a pipeline.

Pay attention that it was designed to open a browser instance to each @Test located in the test class.

This class also has the TestListener annotation which is a custom TestNG listener, and will be described in the next section.

TestListener

The TestListener is a class that implements ITestListener. The following method is used to help logging errors and attach additional information to the test report:

  • onTestStart: add the browser information to the test report
  • onTestFailure: log the exceptions and add a screenshot to the test report
  • onTestSkipped: add the skipped test to the log

Logging

All the log is done by the Log4J using the @Log4j2 annotation.

The log4j2.properties has two strategies: console and file. A file with all the log information will be automatically created on the user folder with test_automation.log filename. If you want to change it, update the appender.file.fileName property value.

The log.error is used to log all the exceptions this architecture might throw. Use log.info or log.debug to log important information, like the users, automatically generated by the factory BookingDataFactory

Parallel execution

The parallel test execution is based on the parallel tests feature on TestNG. This is used by selenium-grid.xml test suite file which has the parallel="tests" attribute and value, whereas test item inside the test suite will execute in parallel. The browser in use for each test should be defined by a parameter, like:

<parameter name="browser" value="chrome"/>

You can define any parallel strategy.

It can be an excellent combination together with the grid strategy.

Execution with Docker Selenium Distributed

This project has the docker-compose.yml file to run the tests in a parallel way using Docker Selenium. To be able to run it in parallel the file has the Dynamic Grid Implementation that will start the container on demand.

This means that Docker Selenium will start a container test for a targeting browser.

Please note that you need to do the following actions before running it in parallel:

  • Docker installed
  • Pull the images for Chrome Edge and Firefox - Optional
    • Images are pulled if not available and initial test execution will be slow
      • docker pull selenium-standalog-chrome
      • docker pull selenium-standalog-firefox
      • docker pull selenium/standalone-edge
    • If you are using a MacBook with either M1 or M2 chip you must check the following experimental feature in Docker Desktop: Settings -> Features in development -> Use Rosetta for x86/amd64 emulation on Apple Silicon
  • Pay attention to the grid/config.toml file that has comments for each specific SO
  • Start the Grid by running the following command inside the grid folder
    • docker-compose up
  • Run the project using the following command
mvn test -Pweb-execution -Dsuite=selenium-grid -Dtarget=selenium-grid -Dheadless=true
  • Open the [Selenium Grid] page to see the node status

Configuration files

This project uses a library called Owner. You can find the class related to the property file reader in the following classes:

There are 3 properties (configuration) files located on src/test/java/resources/:

  • general.properties: general configuration as the target execution, browser, base url, timeout, and faker locale
  • grid.properties: url and port for the Selenium grid usage

The properties were divided into three different ones to better separate the responsibilities and enable the changes easy without having a lot of properties inside a single file.

Test Data Factory

Is the utilization of the Factory design pattern with the Fluent Builder to generate dynamic data. The BookingDataFactory has only one factory createBookingData returning a Booking object with dynamic data.

This dynamic data is generated by JavaFaker filling all the fields using the Build pattern. The Booking is the plain Java objects and the BookingBuilder is the builder class.

You can see the usage of the Builder pattern in the BookingDataFactory class.

Reading reference: https://reflectoring.io/objectmother-fluent-builder

Profiles executors on pom.xml

There is a profile called web-execution created to execute the test suite local.xml inside src/test/resources/suites folder. To execute this suite, via the command line you can call the parameter -P and the profile id.

Eg: executing the multi_browser suite

mvn test -Pweb-execution -Dtestng.dtd.http=true 

If you have more than one suite on src/test/resources/suites folder you can parameterize the xml file name. To do this you need:

  • Create a property on pom.xml called suite
<properties>
    <suite>local</suite>
</properties>
  • Change the profile id
<profile>
    <id>web-execution</id>
</profile>   
  • Replace the xml file name to ${suite} on the profile
<configuration>
    <suiteXmlFiles>
        <suiteXmlFile>src/test/resources/suites/${suite}.xml</suiteXmlFile>
    </suiteXmlFiles>
</configuration>
  • Use -Dsuite=suite_name to call the suite
mvn test -Pweb-execution -Dsuite=parallel -Dtestng.dtd.http=true 

Pipeline as a code

The two files of the pipeline as a code are inside pipeline_as_code folder.

  • GitHub Actions to use it inside the GitHub located at .github\workflows
  • Jenkins: Jenkinsfile to be used on a Jenkins pipeline located at pipeline_as_code
  • GitLab CI: .gitlab-ci.yml to be used on a GitLab CI pipeline_as_code

More Repositories

1

restassured-complete-basic-example

A complete API Test Architecture example using Java and RestAssured providing a real-world example and continuous delivery ready.
Java
140
star
2

appium-parallel-execution

A lean, up-to-date, and cross-platform solution to run your mobile tests into a Selenium Grid using Appium.
Java
92
star
3

public-speaking

List of presentation, workshops, and initiatives
66
star
4

100-tips-testing-java

List of 100 tips for Testing with Java
HTML
34
star
5

selenium-java-browser-factory

Example of the Factory design pattern implementation to create browser instances using Selenium WebDriver
Java
22
star
6

java-e2e-test-example

An complete example of a pipeline focusing on API and UI (mobile and web) tests.
Java
19
star
7

health-check-api

An easy way to execute a health check against your API endpoint
Java
14
star
8

appium-read-qrcode

How to read QR content from an Android app using Appium and Zxing
Java
12
star
9

desafio-selenium

Desafios de Selenium WebDriver
Java
10
star
10

palestra-arquitetura-teste-restassured

Repositório da palestra sobre Arquitetura de Teste com RestAssured
Java
8
star
11

appium-cross-platform-example

Appium Cross Platform example using Java
JavaScript
8
star
12

credit-api

Combined API to simulate a credit request (in a Brazilian way!)
Java
8
star
13

3-design-patters-arch-decisions

Repo for the presentation 3 Design Patterns and Architecture Decisions you must use in your project
Java
7
star
14

tdd-exemplo

Exemplo simples sobre como aplicar TDD com um problema de números romanos
Java
6
star
15

appium-workshop

Workshop para aprender os passos iniciais com o Appium
6
star
16

projeto-teste-api-livro-v1

Projeto para iniciar a automação de testes de API do livro "Testes para uma API com Postman e RestAssured"
5
star
17

exemplo-robotium-calabash

Exemplo de teste em aplicações móveis utilizando Robotium (Android) e Calabash (iOS)
Java
5
star
18

eliasnogueira

You can have additional information about me through my social networks and my public-speaking initiatives.
5
star
19

selenium-dynamic-grid-example

Example project that run multi-browser web test automation in parallel using Selenium Grid and Docker
Java
5
star
20

selenium-parallel-execution

Example how to run Selenium tests with Java and TestNG in parallel using a docker container
Java
4
star
21

testes-android-ponta-a-ponta

PHP
4
star
22

testing-alm

Projeto de integração de ferramentas open source a partir de uma ferramenta de automação de teste
Java
4
star
23

selenium-read-qrcode

How to read QR Code content from a web app using Selenium and Zxing
Java
4
star
24

wiremock-service-virtualization

Service Virtualization example using WireMock standalone with JSON files to map the request and responses and Docker to create a persistent container to enable the long-living service.
Dockerfile
4
star
25

exemplo-appium-android-grid

Exemplo de como executar testes com Appium em diferentes dispositivos em uma grid
Java
4
star
26

manage-testing-data-java

Managing different data approaching for using on tests scripts
Java
4
star
27

postman-collection-automacao-testes-api-v1

Coleção do Postman relacionado aos exercícios do livro Testes para uma API com Postman e RestAssured
4
star
28

credito-api

Projeto alvo dos testes do livro Testes para uma API com Postman e RestAssured
Java
3
star
29

simulacao-credito-api

API de Simulação de Crédito que faz parte do livro Automação de Testes de API com RestAssured
Java
3
star
30

javaone-testing-automation

Java
2
star
31

rest-assured-open-api-generator-talk

Simple example from basic REST Assured tests to a better architecture using the OpenAPI Generator
Java
2
star
32

wiremock-credit-restriction-api

Service virtualisation example for the Simulations API
Dockerfile
2
star
33

example-test-data-builder

How to implement and use Test Data Builder
Java
2
star
34

awesome-restassured

2
star
35

credit-restriction-api

This project was created to start the initial steps with test automation for a REST API using RestAssured.
Java
2
star
36

projeto-automacao-unidavi

Java
2
star
37

automacao-fontend-caipiraagil

Projeto que foi desenvolvido na palestra "Automação de front-end Web com métodos Ágeis"
Java
2
star
38

aula-topicos-avancados-teste

Repositório para a aula de Testes Automatizados de Software do Laboratório de Engenharia de Software IV na Unisinos
JavaScript
1
star
39

css-locator-game

Jogo para aprender alguns dos cssSelectors para utilizar na automação de teste para páginas web
JavaScript
1
star
40

restrictions-test

This is the test project for restrictions API. You can see in the readme file the dependent services and projects to be able to use it.
Java
1
star
41

automacao-mobile-ios-android-tdc2016

Exemplo de Automação de Teste para iOs e Android usando Appium - TDC 2016 Florianopolis
Java
1
star
42

basic-pipeline-project-java-selenium

Java
1
star
43

workshop-selenium-grid

Projeto e documentação para a condução do workshop
1
star
44

appium-android-wear

Exemplo de automação para Android Wear com Appium
Java
1
star
45

workshop-api-rest-frisby-base

Projeto base para a automação de uma API REST
JavaScript
1
star
46

parametrizacao-script-teste

Exemplos de parametrização de dados para scripts de automação de teste
Java
1
star
47

automacao-teste-congressodemobile

Java
1
star
48

simulations-client

This is the client project used in the simulations-test to show how we can modularise a test project.
Java
1
star
49

junit-para-testadores-resolvido

Repositório do curso de JUnit para Testadores
Java
1
star
50

junit-para-testadores

1
star
51

credit-simulator-api

This project was created to start the initial steps with test automation for a REST API using RestAssured.
Java
1
star
52

restrictions-client

This is the client project used in the restrictions-test project to show how we can modularise a test project.
Java
1
star
53

pessoa-backend-api

API REST de Cadastro de Pessoa. Aplicação didática para automação de serviços REST
Java
1
star
54

restricao-credito-api

API de Simulação de Crédito que faz parte do livro Automação de Testes de API com RestAssured
Java
1
star