├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ └── test-execution.yml ├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── script └── install_chrome.sh ├── src ├── test │ ├── resources │ │ ├── testdata │ │ │ ├── products.csv │ │ │ ├── products.json │ │ │ ├── login.csv │ │ │ └── login.json │ │ └── config.properties │ └── java │ │ └── io │ │ └── github │ │ └── tahanima │ │ ├── util │ │ ├── TestRetry.java │ │ ├── DataProviderUtil.java │ │ └── TestListener.java │ │ └── e2e │ │ ├── BaseTest.java │ │ ├── ProductsTest.java │ │ └── LoginTest.java └── main │ └── java │ └── io │ └── github │ └── tahanima │ ├── ui │ ├── component │ │ ├── BaseComponent.java │ │ ├── Header.java │ │ └── SideNavMenu.java │ └── page │ │ ├── BasePage.java │ │ ├── ProductsPage.java │ │ └── LoginPage.java │ ├── config │ ├── ConfigurationManager.java │ └── Configuration.java │ ├── dto │ ├── BaseDto.java │ ├── ProductsDto.java │ └── LoginDto.java │ ├── factory │ ├── BasePageFactory.java │ └── BrowserFactory.java │ └── report │ └── ExtentReportManager.java ├── .gitignore ├── LICENSE ├── gradlew.bat ├── gradlew └── README.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: ['https://www.buymeacoffee.com/tahanima'] 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'selenium-java-test-automation-architecture' 2 | 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tahanima/selenium-java-test-automation-architecture/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /script/install_chrome.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -ex 3 | wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb 4 | sudo apt install ./google-chrome-stable_current_amd64.deb -------------------------------------------------------------------------------- /src/test/resources/testdata/products.csv: -------------------------------------------------------------------------------- 1 | Test Case ID,Test Case Description,User Name,Password,URL 2 | TC-1,Logging out should redirect to login page,standard_user,secret_sauce,https://www.saucedemo.com/ -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /src/test/resources/config.properties: -------------------------------------------------------------------------------- 1 | browser=chrome 2 | headless=true 3 | timeout=15 4 | base.url=https://www.saucedemo.com/ 5 | base.test.data.path=src/test/resources/testdata/ 6 | base.report.path=testoutput/report/ 7 | base.screenshot.path=testoutput/screenshot/ -------------------------------------------------------------------------------- /src/test/resources/testdata/products.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "testCaseId": "TC-1", 4 | "testCaseDescription": "Logging out should redirect to login page", 5 | "username": "standard_user", 6 | "password": "secret_sauce", 7 | "url": "https://www.saucedemo.com/" 8 | } 9 | ] 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Gradle 2 | .gradle 3 | .gradletasknamecache 4 | .m2 5 | !gradle-wrapper.jar 6 | 7 | # Generated by build tool 8 | target/ 9 | build/ 10 | 11 | # Generated by IntelliJ IDEA 12 | out 13 | .idea 14 | *.ipr 15 | *.iws 16 | *.iml 17 | atlassian-ide-plugin.xml 18 | 19 | testoutput -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/ui/component/BaseComponent.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.ui.component; 2 | 3 | import org.openqa.selenium.WebDriver; 4 | 5 | /** 6 | * @author tahanima 7 | */ 8 | public abstract class BaseComponent { 9 | 10 | protected WebDriver driver; 11 | 12 | protected BaseComponent(WebDriver driver) { 13 | this.driver = driver; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/config/ConfigurationManager.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.config; 2 | 3 | import org.aeonbits.owner.ConfigCache; 4 | 5 | /** 6 | * @author tahanima 7 | */ 8 | public final class ConfigurationManager { 9 | 10 | private ConfigurationManager() {} 11 | 12 | public static Configuration config() { 13 | return ConfigCache.getOrCreate(Configuration.class); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/ui/component/Header.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.ui.component; 2 | 3 | import org.openqa.selenium.By; 4 | import org.openqa.selenium.WebDriver; 5 | 6 | /** 7 | * @author tahanima 8 | */ 9 | public final class Header extends BaseComponent { 10 | 11 | public Header(WebDriver driver) { 12 | super(driver); 13 | } 14 | 15 | public void clickOnHamburgerIcon() { 16 | driver.findElement(By.id("react-burger-menu-btn")).click(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/ui/component/SideNavMenu.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.ui.component; 2 | 3 | import org.openqa.selenium.By; 4 | import org.openqa.selenium.WebDriver; 5 | 6 | /** 7 | * @author tahanima 8 | */ 9 | public final class SideNavMenu extends BaseComponent { 10 | 11 | public SideNavMenu(WebDriver driver) { 12 | super(driver); 13 | } 14 | 15 | public void clickOnLogout() { 16 | driver.findElement(By.id("logout_sidebar_link")).click(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/dto/BaseDto.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.dto; 2 | 3 | import com.univocity.parsers.annotations.Parsed; 4 | 5 | import lombok.Getter; 6 | import lombok.ToString; 7 | 8 | /** 9 | * @author tahanima 10 | */ 11 | @Getter 12 | @ToString 13 | public class BaseDto { 14 | 15 | @Parsed(field = "Test Case ID", defaultNullRead = "") 16 | private String testCaseId; 17 | 18 | @Parsed(field = "Test Case Description", defaultNullRead = "") 19 | private String testCaseDescription; 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/io/github/tahanima/util/TestRetry.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.util; 2 | 3 | import org.testng.IRetryAnalyzer; 4 | import org.testng.ITestResult; 5 | 6 | /** 7 | * @author tahanima 8 | */ 9 | public class TestRetry implements IRetryAnalyzer { 10 | 11 | private int retryCount = 0; 12 | 13 | @Override 14 | public boolean retry(ITestResult result) { 15 | int maxRetryCount = 2; 16 | 17 | if (retryCount <= maxRetryCount) { 18 | retryCount++; 19 | 20 | return true; 21 | } 22 | 23 | return false; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "gradle" 9 | directory: "/" 10 | schedule: 11 | interval: "daily" 12 | - package-ecosystem: github-actions 13 | directory: "/" 14 | schedule: 15 | interval: "daily" 16 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/dto/ProductsDto.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.dto; 2 | 3 | import com.univocity.parsers.annotations.Parsed; 4 | 5 | import lombok.Getter; 6 | import lombok.ToString; 7 | 8 | /** 9 | * @author tahanima 10 | */ 11 | @Getter 12 | @ToString(callSuper = true) 13 | public final class ProductsDto extends BaseDto { 14 | 15 | @Parsed(field = "User Name", defaultNullRead = "") 16 | private String username; 17 | 18 | @Parsed(field = "Password", defaultNullRead = "") 19 | private String password; 20 | 21 | @Parsed(field = "URL", defaultNullRead = "") 22 | private String url; 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/dto/LoginDto.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.dto; 2 | 3 | import com.univocity.parsers.annotations.Parsed; 4 | 5 | import lombok.Getter; 6 | import lombok.ToString; 7 | 8 | /** 9 | * @author tahanima 10 | */ 11 | @Getter 12 | @ToString(callSuper = true) 13 | public class LoginDto extends BaseDto { 14 | 15 | @Parsed(field = "Username", defaultNullRead = "") 16 | private String username; 17 | 18 | @Parsed(field = "Password", defaultNullRead = "") 19 | private String password; 20 | 21 | @Parsed(field = "Error Message", defaultNullRead = "") 22 | private String errorMessage; 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/config/Configuration.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.config; 2 | 3 | import org.aeonbits.owner.Config; 4 | import org.aeonbits.owner.Config.*; 5 | 6 | /** 7 | * @author tahanima 8 | */ 9 | @LoadPolicy(LoadType.MERGE) 10 | @Sources({"system:properties", "classpath:config.properties"}) 11 | public interface Configuration extends Config { 12 | 13 | @Key("browser") 14 | String browser(); 15 | 16 | @Key("headless") 17 | boolean headless(); 18 | 19 | @Key("timeout") 20 | int timeout(); 21 | 22 | @Key("base.url") 23 | String baseUrl(); 24 | 25 | @Key("base.test.data.path") 26 | String baseTestDataPath(); 27 | 28 | @Key("base.report.path") 29 | String baseReportPath(); 30 | 31 | @Key("base.screenshot.path") 32 | String baseScreenshotPath(); 33 | } 34 | -------------------------------------------------------------------------------- /.github/workflows/test-execution.yml: -------------------------------------------------------------------------------- 1 | name: Selenium Java CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v4 16 | - name: Set up JDK 11 17 | uses: actions/setup-java@v4 18 | with: 19 | distribution: 'zulu' 20 | java-version: 11 21 | - name: Install Google Chrome 22 | run: | 23 | chmod +x ./script/install_chrome.sh 24 | ./script/install_chrome.sh 25 | - name: Grant execute permission for gradlew 26 | run: chmod +x gradlew 27 | - name: Run Smoke Tests in Chrome 28 | run: ./gradlew test --info -Dgroups=smoke 29 | - name: Run Regression Tests in Chrome 30 | run: ./gradlew test --info -Dgroups=regression 31 | 32 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/ui/page/BasePage.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.ui.page; 2 | 3 | import static io.github.tahanima.config.ConfigurationManager.config; 4 | 5 | import com.assertthat.selenium_shutterbug.core.Shutterbug; 6 | 7 | import org.openqa.selenium.WebDriver; 8 | import org.openqa.selenium.support.PageFactory; 9 | 10 | /** 11 | * @author tahanima 12 | */ 13 | public abstract class BasePage { 14 | 15 | protected WebDriver driver; 16 | 17 | public void initDriverAndElements(final WebDriver webdriver) { 18 | this.driver = webdriver; 19 | 20 | PageFactory.initElements(driver, this); 21 | } 22 | 23 | public void initComponents() {} 24 | 25 | public String getUrl() { 26 | return driver.getCurrentUrl(); 27 | } 28 | 29 | public void captureScreenshot(String fileName) { 30 | Shutterbug.shootPage(driver).withName(fileName).save(config().baseScreenshotPath()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/ui/page/ProductsPage.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.ui.page; 2 | 3 | import io.github.tahanima.ui.component.Header; 4 | import io.github.tahanima.ui.component.SideNavMenu; 5 | 6 | import org.openqa.selenium.WebElement; 7 | import org.openqa.selenium.support.FindBy; 8 | 9 | /** 10 | * @author tahanima 11 | */ 12 | public final class ProductsPage extends BasePage { 13 | 14 | private Header header; 15 | private SideNavMenu sideNavMenu; 16 | 17 | @FindBy(className = "title") 18 | private WebElement lblTitle; 19 | 20 | @Override 21 | public void initComponents() { 22 | header = new Header(driver); 23 | sideNavMenu = new SideNavMenu(driver); 24 | } 25 | 26 | public void clickOnLogout() { 27 | header.clickOnHamburgerIcon(); 28 | sideNavMenu.clickOnLogout(); 29 | } 30 | 31 | public String getTitle() { 32 | return lblTitle.getText(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/factory/BasePageFactory.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.factory; 2 | 3 | import io.github.tahanima.ui.page.BasePage; 4 | 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.openqa.selenium.WebDriver; 7 | 8 | /** 9 | * @author tahanima 10 | */ 11 | @Slf4j 12 | public final class BasePageFactory { 13 | 14 | private BasePageFactory() {} 15 | 16 | public static T createInstance( 17 | final WebDriver driver, final Class clazz) { 18 | try { 19 | BasePage instance = clazz.getDeclaredConstructor().newInstance(); 20 | 21 | instance.initDriverAndElements(driver); 22 | instance.initComponents(); 23 | 24 | return clazz.cast(instance); 25 | } catch (Exception e) { 26 | log.error("BasePageFactory::createInstance", e); 27 | } 28 | 29 | throw new NullPointerException("Page class instantiation failed."); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Tahanima Chowdhury 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/test/java/io/github/tahanima/e2e/BaseTest.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.e2e; 2 | 3 | import static io.github.tahanima.config.ConfigurationManager.config; 4 | 5 | import io.github.tahanima.factory.BasePageFactory; 6 | import io.github.tahanima.factory.BrowserFactory; 7 | import io.github.tahanima.ui.page.LoginPage; 8 | import io.github.tahanima.util.TestListener; 9 | 10 | import org.openqa.selenium.WebDriver; 11 | import org.testng.annotations.AfterClass; 12 | import org.testng.annotations.BeforeClass; 13 | import org.testng.annotations.Listeners; 14 | 15 | /** 16 | * @author tahanima 17 | */ 18 | @Listeners(TestListener.class) 19 | public abstract class BaseTest { 20 | 21 | private final WebDriver driver = 22 | BrowserFactory.valueOf(config().browser().toUpperCase()).getDriver(); 23 | protected LoginPage loginPage; 24 | 25 | protected String getTestDataFilePath(String path) { 26 | return config().baseTestDataPath() + path; 27 | } 28 | 29 | protected String getScreenshotFilePath(String path) { 30 | return config().baseScreenshotPath() + path; 31 | } 32 | 33 | @BeforeClass(alwaysRun = true) 34 | public void setup() { 35 | loginPage = BasePageFactory.createInstance(driver, LoginPage.class); 36 | } 37 | 38 | @AfterClass(alwaysRun = true) 39 | public void tearDown() { 40 | driver.quit(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/report/ExtentReportManager.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.report; 2 | 3 | import static io.github.tahanima.config.ConfigurationManager.config; 4 | 5 | import com.aventstack.extentreports.ExtentReports; 6 | import com.aventstack.extentreports.reporter.ExtentSparkReporter; 7 | 8 | import org.apache.commons.lang3.StringUtils; 9 | 10 | import java.text.SimpleDateFormat; 11 | import java.util.Date; 12 | import java.util.Objects; 13 | 14 | /** 15 | * @author tahanima 16 | */ 17 | public final class ExtentReportManager { 18 | 19 | private ExtentReportManager() {} 20 | 21 | public static ExtentReports createReport() { 22 | String currentDate = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()); 23 | String fileName = 24 | String.format("%sE2ETestReport_%s.html", config().baseReportPath(), currentDate); 25 | 26 | ExtentReports extentReport = new ExtentReports(); 27 | ExtentSparkReporter spark = new ExtentSparkReporter(fileName); 28 | 29 | spark.config().setTimeStampFormat("dd MMM yyyy HH:mm:ss z"); 30 | spark.config().setTimelineEnabled(false); 31 | 32 | extentReport.attachReporter(spark); 33 | extentReport.setSystemInfo("Platform", System.getProperty("os.name")); 34 | extentReport.setSystemInfo("Version", System.getProperty("os.version")); 35 | extentReport.setSystemInfo("Browser", StringUtils.capitalize(config().browser())); 36 | extentReport.setSystemInfo("Context URL", config().baseUrl()); 37 | extentReport.setSystemInfo( 38 | "Test Group", 39 | StringUtils.capitalize( 40 | Objects.toString(System.getProperty("groups"), "regression"))); 41 | 42 | return extentReport; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/resources/testdata/login.csv: -------------------------------------------------------------------------------- 1 | Test Case ID,Test Case Description,Username,Password,Error Message 2 | TC-1,Correct username and correct password should redirect to 'Products' page,standard_user,secret_sauce, 3 | TC-1,Correct username and correct password should redirect to 'Products' page,problem_user,secret_sauce, 4 | TC-1,Correct username and correct password should redirect to 'Products' page,performance_glitch_user,secret_sauce, 5 | TC-2,Incorrect username and correct password should produce error message,username,secret_sauce,Epic sadface: Username and password do not match any user in this service 6 | TC-2,Correct username and incorrect password should produce error message,standard_user,password,Epic sadface: Username and password do not match any user in this service 7 | TC-2,Correct username and incorrect password should produce error message,locked_out_user,password,Epic sadface: Username and password do not match any user in this service 8 | TC-2,Correct username and incorrect password should produce error message,problem_user,password,Epic sadface: Username and password do not match any user in this service 9 | TC-2,Correct username and incorrect password should produce error message,performance_glitch_user,password,Epic sadface: Username and password do not match any user in this service 10 | TC-2,Incorrect username and incorrect password should produce error message,demo_username,demo_password,Epic sadface: Username and password do not match any user in this service 11 | TC-2,Blank username should produce error message,,demo_password,Epic sadface: Username is required 12 | TC-2,Blank password should produce error message,demo_username,,Epic sadface: Password is required 13 | TC-2,Should produce error message for locked out user,locked_out_user,secret_sauce,"Epic sadface: Sorry, this user has been locked out." -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/ui/page/LoginPage.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.ui.page; 2 | 3 | import static io.github.tahanima.config.ConfigurationManager.config; 4 | 5 | import io.github.tahanima.factory.BasePageFactory; 6 | 7 | import org.openqa.selenium.By; 8 | import org.openqa.selenium.WebElement; 9 | import org.openqa.selenium.support.FindBy; 10 | 11 | /** 12 | * @author tahanima 13 | */ 14 | public final class LoginPage extends BasePage { 15 | 16 | @FindBy(id = "user-name") 17 | private WebElement txtUsername; 18 | 19 | @FindBy(id = "password") 20 | private WebElement txtPassword; 21 | 22 | @FindBy(id = "login-button") 23 | private WebElement btnLogin; 24 | 25 | public LoginPage open() { 26 | driver.get(config().baseUrl()); 27 | 28 | return this; 29 | } 30 | 31 | private void clearAndType(final WebElement elem, final String text) { 32 | elem.clear(); 33 | elem.sendKeys(text); 34 | } 35 | 36 | public LoginPage typeUsername(final String username) { 37 | clearAndType(txtUsername, username); 38 | 39 | return this; 40 | } 41 | 42 | public LoginPage typePassword(final String password) { 43 | clearAndType(txtPassword, password); 44 | 45 | return this; 46 | } 47 | 48 | public String getErrorMessage() { 49 | return driver.findElement(By.className("error-message-container")) 50 | .findElement(By.tagName("h3")) 51 | .getText(); 52 | } 53 | 54 | public ProductsPage clickOnLogin() { 55 | btnLogin.click(); 56 | 57 | return BasePageFactory.createInstance(driver, ProductsPage.class); 58 | } 59 | 60 | public ProductsPage loginAs(String username, String password) { 61 | open(); 62 | typeUsername(username); 63 | typePassword(password); 64 | 65 | return clickOnLogin(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/io/github/tahanima/factory/BrowserFactory.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.factory; 2 | 3 | import static io.github.tahanima.config.ConfigurationManager.config; 4 | 5 | import org.openqa.selenium.WebDriver; 6 | import org.openqa.selenium.chrome.ChromeDriver; 7 | import org.openqa.selenium.chrome.ChromeOptions; 8 | import org.openqa.selenium.firefox.FirefoxDriver; 9 | import org.openqa.selenium.firefox.FirefoxOptions; 10 | 11 | import java.time.Duration; 12 | 13 | /** 14 | * @author tahanima 15 | */ 16 | public enum BrowserFactory { 17 | 18 | CHROME { 19 | @Override 20 | public WebDriver getDriver() { 21 | WebDriver driver = new ChromeDriver(getOptions()); 22 | 23 | driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(config().timeout())); 24 | driver.manage().window().maximize(); 25 | 26 | return driver; 27 | } 28 | 29 | private ChromeOptions getOptions() { 30 | ChromeOptions options = new ChromeOptions(); 31 | 32 | options.setAcceptInsecureCerts(true); 33 | 34 | if (Boolean.TRUE.equals(config().headless())) { 35 | options.addArguments("--headless=new"); 36 | } 37 | 38 | return options; 39 | } 40 | }, 41 | 42 | FIREFOX { 43 | @Override 44 | public WebDriver getDriver() { 45 | WebDriver driver = new FirefoxDriver(getOptions()); 46 | 47 | driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(config().timeout())); 48 | driver.manage().window().maximize(); 49 | 50 | return driver; 51 | } 52 | 53 | private FirefoxOptions getOptions() { 54 | FirefoxOptions options = new FirefoxOptions(); 55 | 56 | options.setAcceptInsecureCerts(true); 57 | 58 | if (Boolean.TRUE.equals(config().headless())) { 59 | options.addArguments("--headless=new"); 60 | } 61 | 62 | return options; 63 | } 64 | }; 65 | 66 | public abstract WebDriver getDriver(); 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/io/github/tahanima/e2e/ProductsTest.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.e2e; 2 | 3 | import static io.github.tahanima.util.DataProviderUtil.processTestData; 4 | 5 | import static org.assertj.core.api.AssertionsForClassTypes.assertThat; 6 | 7 | import io.github.tahanima.dto.ProductsDto; 8 | import io.github.tahanima.util.TestRetry; 9 | 10 | import org.testng.ITestNGMethod; 11 | import org.testng.ITestResult; 12 | import org.testng.annotations.AfterMethod; 13 | import org.testng.annotations.DataProvider; 14 | import org.testng.annotations.Test; 15 | 16 | import java.lang.reflect.Method; 17 | 18 | /** 19 | * @author tahanima 20 | */ 21 | public final class ProductsTest extends BaseTest { 22 | 23 | private static final String FILE_PATH = "products.json"; 24 | 25 | @DataProvider(name = "productsData") 26 | public Object[][] getProductsData(final Method testMethod) { 27 | String testCaseId = testMethod.getAnnotation(Test.class).testName(); 28 | 29 | return processTestData(ProductsDto.class, getTestDataFilePath(FILE_PATH), testCaseId); 30 | } 31 | 32 | @AfterMethod(alwaysRun = true) 33 | public void captureScreenshotOnFailure(ITestResult result) { 34 | ITestNGMethod method = result.getMethod(); 35 | 36 | if (ITestResult.FAILURE == result.getStatus()) { 37 | loginPage.captureScreenshot( 38 | String.format( 39 | "%s_%s_%s", 40 | method.getRealClass().getSimpleName(), 41 | method.getMethodName(), 42 | method.getParameterInvocationCount())); 43 | } 44 | } 45 | 46 | @Test( 47 | testName = "TC-1", 48 | dataProvider = "productsData", 49 | groups = {"smoke", "regression"}, 50 | retryAnalyzer = TestRetry.class) 51 | public void testSuccessfulLogout(final ProductsDto data) { 52 | loginPage.loginAs(data.getUsername(), data.getPassword()).clickOnLogout(); 53 | 54 | assertThat(loginPage.getUrl()).isEqualTo(data.getUrl()); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/io/github/tahanima/e2e/LoginTest.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.e2e; 2 | 3 | import static io.github.tahanima.util.DataProviderUtil.processTestData; 4 | 5 | import static org.assertj.core.api.AssertionsForClassTypes.assertThat; 6 | 7 | import io.github.tahanima.dto.LoginDto; 8 | import io.github.tahanima.ui.page.ProductsPage; 9 | import io.github.tahanima.util.TestRetry; 10 | 11 | import org.testng.ITestNGMethod; 12 | import org.testng.ITestResult; 13 | import org.testng.annotations.AfterMethod; 14 | import org.testng.annotations.DataProvider; 15 | import org.testng.annotations.Test; 16 | 17 | import java.lang.reflect.Method; 18 | 19 | /** 20 | * @author tahanima 21 | */ 22 | public final class LoginTest extends BaseTest { 23 | 24 | private static final String FILE_PATH = "login.csv"; 25 | 26 | @DataProvider(name = "loginData") 27 | public Object[][] getLoginData(final Method testMethod) { 28 | String testCaseId = testMethod.getAnnotation(Test.class).testName(); 29 | 30 | return processTestData(LoginDto.class, getTestDataFilePath(FILE_PATH), testCaseId); 31 | } 32 | 33 | @AfterMethod(alwaysRun = true) 34 | public void captureScreenshotOnFailure(ITestResult result) { 35 | ITestNGMethod method = result.getMethod(); 36 | 37 | if (ITestResult.FAILURE == result.getStatus()) { 38 | loginPage.captureScreenshot( 39 | String.format( 40 | "%s_%s_%s", 41 | method.getRealClass().getSimpleName(), 42 | method.getMethodName(), 43 | method.getParameterInvocationCount())); 44 | } 45 | } 46 | 47 | @Test( 48 | testName = "TC-1", 49 | dataProvider = "loginData", 50 | groups = {"smoke", "regression"}, 51 | retryAnalyzer = TestRetry.class) 52 | public void testCorrectUserNameAndCorrectPassword(final LoginDto data) { 53 | ProductsPage productsPage = loginPage.loginAs(data.getUsername(), data.getPassword()); 54 | 55 | assertThat(productsPage.getTitle()).isEqualTo("Products"); 56 | } 57 | 58 | @Test( 59 | testName = "TC-2", 60 | dataProvider = "loginData", 61 | groups = {"validation", "regression"}, 62 | retryAnalyzer = TestRetry.class) 63 | public void testImproperCredentialsShouldGiveErrorMessage(final LoginDto data) { 64 | loginPage.loginAs(data.getUsername(), data.getPassword()); 65 | 66 | assertThat(loginPage.getErrorMessage()).isEqualTo(data.getErrorMessage()); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/test/resources/testdata/login.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "testCaseId": "TC-1", 4 | "testCaseDescription": "Correct username and correct password should redirect to 'Products' page", 5 | "username": "standard_user", 6 | "password": "secret_sauce", 7 | "errorMessage": "" 8 | }, 9 | { 10 | "testCaseId": "TC-1", 11 | "testCaseDescription": "Correct username and correct password should redirect to 'Products' page", 12 | "username": "problem_user", 13 | "password": "secret_sauce", 14 | "errorMessage": "" 15 | }, 16 | { 17 | "testCaseId": "TC-1", 18 | "testCaseDescription": "Correct username and correct password should redirect to 'Products' page", 19 | "username": "performance_glitch_user", 20 | "password": "secret_sauce", 21 | "errorMessage": "" 22 | }, 23 | { 24 | "testCaseId": "TC-2", 25 | "testCaseDescription": "Incorrect username and correct password should produce errorMessage", 26 | "username": "username", 27 | "password": "secret_sauce", 28 | "errorMessage": "Epic sadface: Username and password do not match any user in this service" 29 | }, 30 | { 31 | "testCaseId": "TC-2", 32 | "testCaseDescription": "Correct username and incorrect password should produce errorMessage", 33 | "username": "standard_user", 34 | "password": "password", 35 | "errorMessage": "Epic sadface: Username and password do not match any user in this service" 36 | }, 37 | { 38 | "testCaseId": "TC-2", 39 | "testCaseDescription": "Correct username and incorrect password should produce errorMessage", 40 | "username": "locked_out_user", 41 | "password": "password", 42 | "errorMessage": "Epic sadface: Username and password do not match any user in this service" 43 | }, 44 | { 45 | "testCaseId": "TC-2", 46 | "testCaseDescription": "Correct username and incorrect password should produce errorMessage", 47 | "username": "problem_user", 48 | "password": "password", 49 | "errorMessage": "Epic sadface: Username and password do not match any user in this service" 50 | }, 51 | { 52 | "testCaseId": "TC-2", 53 | "testCaseDescription": "Correct username and incorrect password should produce errorMessage", 54 | "username": "performance_glitch_user", 55 | "password": "password", 56 | "errorMessage": "Epic sadface: Username and password do not match any user in this service" 57 | }, 58 | { 59 | "testCaseId": "TC-2", 60 | "testCaseDescription": "Incorrect username and incorrect password should produce errorMessage", 61 | "username": "demo_username", 62 | "password": "demo_password", 63 | "errorMessage": "Epic sadface: Username and password do not match any user in this service" 64 | }, 65 | { 66 | "testCaseId": "TC-2", 67 | "testCaseDescription": "Blank username should produce errorMessage", 68 | "username": "", 69 | "password": "demo_password", 70 | "errorMessage": "Epic sadface: Username is required" 71 | }, 72 | { 73 | "testCaseId": "TC-2", 74 | "testCaseDescription": "Blank password should produce errorMessage", 75 | "username": "demo_username", 76 | "password": "", 77 | "errorMessage": "Epic sadface: Password is required" 78 | }, 79 | { 80 | "testCaseId": "TC-2", 81 | "testCaseDescription": "Should produce errorMessage for locked out user", 82 | "username": "locked_out_user", 83 | "password": "secret_sauce", 84 | "errorMessage": "Epic sadface: Sorry, this user has been locked out." 85 | } 86 | ] 87 | -------------------------------------------------------------------------------- /src/test/java/io/github/tahanima/util/DataProviderUtil.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.util; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.reflect.TypeToken; 5 | import com.univocity.parsers.csv.CsvParserSettings; 6 | import com.univocity.parsers.csv.CsvRoutines; 7 | 8 | import io.github.tahanima.dto.BaseDto; 9 | 10 | import lombok.extern.slf4j.Slf4j; 11 | 12 | import java.io.FileInputStream; 13 | import java.io.IOException; 14 | import java.io.InputStreamReader; 15 | import java.nio.charset.StandardCharsets; 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | 19 | /** 20 | * @author tahanima 21 | */ 22 | @Slf4j 23 | public final class DataProviderUtil { 24 | 25 | private DataProviderUtil() {} 26 | 27 | public static Object[][] processTestData( 28 | Class clazz, String fileName, String id) { 29 | if (fileName.endsWith(".csv")) return processCsv(clazz, fileName, id); 30 | 31 | if (fileName.endsWith(".json")) return processJson(clazz, fileName, id); 32 | 33 | return new Object[0][0]; 34 | } 35 | 36 | private static Object[][] processCsv( 37 | Class clazz, String fileName, String id) { 38 | var settings = new CsvParserSettings(); 39 | 40 | settings.getFormat().setLineSeparator("\n"); 41 | 42 | var routines = new CsvRoutines(settings); 43 | 44 | try (var reader = 45 | new InputStreamReader(new FileInputStream(fileName), StandardCharsets.UTF_8)) { 46 | ArrayList> testData = new ArrayList<>(); 47 | 48 | routines.iterate(clazz, reader) 49 | .forEach( 50 | e -> { 51 | if (e.getTestCaseId().equals(id)) { 52 | testData.add( 53 | new ArrayList<>() { 54 | { 55 | add(e); 56 | } 57 | }); 58 | } 59 | }); 60 | 61 | return toArray(testData); 62 | } catch (IOException e) { 63 | log.error("DataProviderUtil::processCsv", e); 64 | } 65 | 66 | return new Object[0][0]; 67 | } 68 | 69 | private static Object[][] processJson( 70 | Class clazz, String fileName, String id) { 71 | try (var reader = 72 | new InputStreamReader(new FileInputStream(fileName), StandardCharsets.UTF_8)) { 73 | ArrayList> testData = new ArrayList<>(); 74 | List jsonData = 75 | new Gson() 76 | .fromJson( 77 | reader, 78 | TypeToken.getParameterized(List.class, clazz).getType()); 79 | 80 | jsonData.forEach( 81 | e -> { 82 | if (e.getTestCaseId().equals(id)) { 83 | testData.add( 84 | new ArrayList<>() { 85 | { 86 | add(e); 87 | } 88 | }); 89 | } 90 | }); 91 | 92 | return toArray(testData); 93 | } catch (IOException e) { 94 | log.error("DataProviderUtil::processJson", e); 95 | } 96 | return new Object[0][0]; 97 | } 98 | 99 | private static Object[][] toArray(ArrayList> testData) { 100 | int noOfRows = testData.size(); 101 | Object[][] testDataArray = new Object[noOfRows][1]; 102 | 103 | for (int i = 0; i < noOfRows; i++) { 104 | testDataArray[i][0] = testData.get(i).get(0); 105 | } 106 | 107 | return testDataArray; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/test/java/io/github/tahanima/util/TestListener.java: -------------------------------------------------------------------------------- 1 | package io.github.tahanima.util; 2 | 3 | import static io.github.tahanima.config.ConfigurationManager.config; 4 | 5 | import com.aventstack.extentreports.ExtentReports; 6 | import com.aventstack.extentreports.MediaEntityBuilder; 7 | 8 | import io.github.tahanima.dto.BaseDto; 9 | import io.github.tahanima.report.ExtentReportManager; 10 | 11 | import org.apache.commons.text.StringEscapeUtils; 12 | import org.testng.ITestContext; 13 | import org.testng.ITestListener; 14 | import org.testng.ITestNGMethod; 15 | import org.testng.ITestResult; 16 | 17 | /** 18 | * @author tahanima 19 | */ 20 | public class TestListener implements ITestListener { 21 | 22 | private static final ExtentReports REPORT = ExtentReportManager.createReport(); 23 | 24 | @Override 25 | public void onTestSuccess(ITestResult result) { 26 | ITestNGMethod method = result.getMethod(); 27 | String testCaseId = "#"; 28 | String testCaseDescription = ""; 29 | String testData = "No data parameters are found."; 30 | 31 | if (result.getParameters().length > 0) { 32 | BaseDto data = (BaseDto) result.getParameters()[0]; 33 | testCaseId = data.getTestCaseId(); 34 | testCaseDescription = data.getTestCaseDescription(); 35 | testData = StringEscapeUtils.escapeHtml4(data.toString()); 36 | } 37 | 38 | REPORT.createTest(String.format("[%s] %s", testCaseId, method.getMethodName())) 39 | .assignCategory(method.getRealClass().getSimpleName()) 40 | .pass( 41 | String.format( 42 | "Test Case Description: %s

Test Data: %s

Test Execution Time: %.3f seconds", 43 | testCaseDescription, 44 | testData, 45 | (double) (result.getEndMillis() - result.getStartMillis()) 46 | / 1000.0)); 47 | } 48 | 49 | @Override 50 | public void onTestFailure(ITestResult result) { 51 | ITestNGMethod method = result.getMethod(); 52 | String testCaseId = "#"; 53 | String testCaseDescription = ""; 54 | String testData = "No data parameters are found."; 55 | 56 | if (result.getParameters().length > 0) { 57 | BaseDto data = (BaseDto) result.getParameters()[0]; 58 | testCaseId = data.getTestCaseId(); 59 | testCaseDescription = data.getTestCaseDescription(); 60 | testData = StringEscapeUtils.escapeHtml4(data.toString()); 61 | } 62 | 63 | REPORT.createTest(String.format("[%s] %s", testCaseId, method.getMethodName())) 64 | .assignCategory(method.getRealClass().getSimpleName()) 65 | .fail( 66 | String.format( 67 | "Test Case Description: %s

Test Data: %s

Test Execution Time: %.3f seconds", 68 | testCaseDescription, 69 | testData, 70 | (double) (result.getEndMillis() - result.getStartMillis()) 71 | / 1000.0)) 72 | .fail( 73 | result.getThrowable(), 74 | MediaEntityBuilder.createScreenCaptureFromPath( 75 | String.format( 76 | "../../%s%s_%s_%s.png", 77 | config().baseScreenshotPath(), 78 | method.getRealClass().getSimpleName(), 79 | method.getMethodName(), 80 | method.getParameterInvocationCount())) 81 | .build()); 82 | } 83 | 84 | @Override 85 | public void onTestSkipped(ITestResult result) { 86 | ITestNGMethod method = result.getMethod(); 87 | String testCaseId = "#"; 88 | String testCaseDescription = ""; 89 | String testData = "No data parameters are found."; 90 | 91 | if (result.getParameters().length > 0) { 92 | BaseDto data = (BaseDto) result.getParameters()[0]; 93 | testCaseId = data.getTestCaseId(); 94 | testCaseDescription = data.getTestCaseDescription(); 95 | testData = StringEscapeUtils.escapeHtml4(data.toString()); 96 | } 97 | 98 | REPORT.createTest(String.format("[%s] %s", testCaseId, method.getMethodName())) 99 | .assignCategory(method.getRealClass().getSimpleName()) 100 | .skip( 101 | String.format( 102 | "Test Case Description: %s

Test Data: %s

Test Execution Time: %.3f seconds", 103 | testCaseDescription, 104 | testData, 105 | (double) (result.getEndMillis() - result.getStartMillis()) 106 | / 1000.0)); 107 | } 108 | 109 | @Override 110 | public void onFinish(ITestContext context) { 111 | REPORT.flush(); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MSYS* | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Selenium Java Test Automation Architecture 2 | 3 | Ready-to-use UI Test Automation Architecture using Java and Selenium WebDriver. 4 | 5 | ## Installation Steps 6 | 7 | In order to use the framework: 8 | 9 | 1. [Fork](https://github.com/Tahanima/selenium-java-test-automation-architecture/fork) the repository. 10 | 2. Clone, i.e, download your copy of the repository to your local machine using 11 | ``` 12 | git clone https://github.com/[your_username]/selenium-java-test-automation-architecture.git 13 | ``` 14 | 3. Import the project in [IntelliJ IDEA](https://www.jetbrains.com/idea/download/). 15 | 4. Make your desired changes. 16 | 5. Use IntelliJ IDEA to run your desired tests. Alternatively, you can use the terminal to run the tests, for example `./gradlew test -Dbrowser=firefox -Dheadless=false` to run all the tests using the firefox browser in headful mode. 17 | 6. To see the report, go to the `testoutput` folder in the project root and then go to the `report` folder. 18 | 19 | ## Languages and Frameworks 20 | 21 | The project uses the following: 22 | 23 | - *[Java 11](https://openjdk.java.net/projects/jdk/11/)* as the programming language. 24 | - *[Selenium WebDriver](https://www.selenium.dev/)* as the web browser automation framework using the Java binding. 25 | - *[Univocity Parsers](https://www.univocity.com/pages/univocity_parsers_tutorial)* to parse and handle CSV files. 26 | - *[TestNG](https://testng.org/doc/)* as the testing framework. 27 | - *[AssertJ](https://assertj.github.io/doc/)* as the assertion library. 28 | - *[Lombok](https://projectlombok.org/)* to generate getters. 29 | - *[Owner](http://owner.aeonbits.org/)* to minimize the code to handle properties file. 30 | - *[Extent Reports](https://www.extentreports.com/)* as the test reporting strategy. 31 | - *[Selenium Shutterbug](https://github.com/assertthat/selenium-shutterbug)* for capturing screenshots. 32 | - *[Gradle](https://gradle.org/)* as the Java build tool. 33 | - *[IntelliJ IDEA](https://www.jetbrains.com/idea/)* as the IDE. 34 | 35 | ## Project Structure 36 | 37 | The project is structured as follows: 38 | 39 | ```bash 40 | 📦 selenium-java-test-automation-architecture 41 | ├─ .github 42 | │  ├─ FUNDING.yml 43 | │  ├─ dependabot.yml 44 | │  └─ workflows 45 | │     └─ test-execution.yml 46 | ├─ .gitignore 47 | ├─ LICENSE 48 | ├─ README.md 49 | ├─ build.gradle 50 | ├─ gradle 51 | │  └─ wrapper 52 | │     ├─ gradle-wrapper.jar 53 | │     └─ gradle-wrapper.properties 54 | ├─ gradlew 55 | ├─ gradlew.bat 56 | ├─ script 57 | │  └─ install_chrome.sh 58 | ├─ settings.gradle 59 | └─ src 60 |    ├─ main 61 |    │  └─ java 62 |    │     └─ io 63 |    │        └─ github 64 |    │           └─ tahanima 65 |    │              ├─ config 66 |    │              │  ├─ Configuration.java 67 |    │              │  └─ ConfigurationManager.java 68 |    │              ├─ dto 69 |    │              │  ├─ BaseDto.java 70 |    │              │  ├─ LoginDto.java 71 |    │              │  └─ ProductsDto.java 72 |    │              ├─ factory 73 |    │              │  ├─ BasePageFactory.java 74 |    │              │  └─ BrowserFactory.java 75 |    │              ├─ report 76 |    │              │  └─ ExtentReportManager.java 77 |    │              └─ ui 78 |    │                 ├─ component 79 |    │                 │  ├─ BaseComponent.java 80 |    │                 │  ├─ Header.java 81 |    │                 │  └─ SideNavMenu.java 82 |    │                 └─ page 83 |    │                    ├─ BasePage.java 84 |    │                    ├─ LoginPage.java 85 |    │                    └─ ProductsPage.java 86 |    └─ test 87 |       ├─ java 88 |       │  └─ io 89 |       │     └─ github 90 |       │        └─ tahanima 91 |       │           ├─ e2e 92 |       │           │  ├─ BaseTest.java 93 |       │           │  ├─ LoginTest.java 94 |       │           │  └─ ProductsTest.java 95 |       │           └─ util 96 |       │              ├─ DataProviderUtil.java 97 |       │              ├─ TestListener.java 98 |       │              └─ TestRetry.java 99 |       └─ resources 100 |          ├─ config.properties 101 |          └─ testdata 102 |             ├─ login.csv 103 |             ├─ login.json 104 |             ├─ products.csv 105 |             └─ products.json 106 | ``` 107 | 108 | ## Basic Usage 109 | 110 | - ### Configuration 111 | The project uses a [*config.properties*](./src/test/resources/config.properties) file to manage global configurations such as browser type and base url. 112 | 113 | 1. To add a new property, register a new entry in this file. 114 | ``` 115 | key=value 116 | ``` 117 | 118 | Then, add a method in the [*Configuration*](./src/main/java/io/github/tahanima/config/Configuration.java) interface in the below format. 119 | ```java 120 | @Key("key") 121 | dataType key(); 122 | ``` 123 | 124 | For example, let's say I want to add a new property named `context` with the value `dev`. In the `config.properties` file, I'll add: 125 | ``` 126 | context=dev 127 | ``` 128 | 129 | In the `Configuration` interface, I'll add: 130 | ```java 131 | @Key("context") 132 | String context(); 133 | ``` 134 | 135 | To use your newly created property, you need to use the below import statement. 136 | ```java 137 | import static io.github.tahanima.config.ConfigurationManager.config; 138 | ``` 139 | 140 | Then, you can call `config().key()` to retrieve the value of your newly created property. For the example I've provided, I need to call `config().context()`. 141 | 142 | 2. You can supply the properties present in the `config.properties` file as system properties in your test via gradle. 143 | ```bash 144 | ./gradlew test -Dkey1=value1 -Dkey2=value2 145 | ``` 146 | 147 | - ### Test Data 148 | The project uses *csv* or *json* file to store test data and [*univocity-parsers*](https://github.com/uniVocity/univocity-parsers) to retrieve the data and map it to a Java bean. 149 | 150 | To add configurations for new test data, add a new Java bean in the [*dto*](./src/main/java/io/github/tahanima/dto) package. For example, let's say I want to add test data for a `User` with the attributes `First Name` and `Last Name`. The code for this is as follows: 151 | 152 | ```java 153 | package io.github.tahanima.dto; 154 | 155 | import com.univocity.parsers.annotations.Parsed; 156 | 157 | import lombok.Getter; 158 | import lombok.ToString; 159 | 160 | @Getter 161 | @ToString(callSuper = true) 162 | public class UserDto extends BaseDto { 163 | 164 | @Parsed(field = "First Name", defaultNullRead = "") 165 | private String firstName; 166 | 167 | @Parsed(field = "Last Name", defaultNullRead = "") 168 | private String lastName; 169 | } 170 | ``` 171 | Note that the class extends from BaseDto and thus, inherits the attributes `Test Case ID` and `Test Case Description`. 172 | 173 | Now, in the [*testdata*](./src/test/resources/testdata) folder you can add a csv file `user.csv` for `User` with the below contents and use it in your tests. 174 | ``` 175 | Test Case ID,Test Case Description,First Name,Last Name 176 | TC-1,Successful user creation,Tahanima,Chowdhury 177 | ``` 178 | 179 | Alternately, you can use a json file `user.json` with the below contents and use it in your tests. 180 | ```json 181 | [ 182 | { 183 | "testCaseId": "TC-1", 184 | "testCaseDescription": "Successful user creation", 185 | "firstName": "Tahanima", 186 | "lastName": "Chowdhury" 187 | } 188 | ] 189 | ``` 190 | For reference, check [this](./src/main/java/io/github/tahanima/dto/LoginDto.java), [this](./src/test/resources/testdata/login.csv) and [this](./src/test/java/io/github/tahanima/e2e/LoginTest.java). 191 | 192 | - ### Browser 193 | The project contains the implementation of the *Chrome* and *Firefox* browsers. If you want to include an implementation of a new browser type, add the relevant codes in the [*BrowserFactory*](./src/main/java/io/github/tahanima/factory/BrowserFactory.java) enum. 194 | 195 | For example, let's say I want to add the `Edge` browser to the `BrowserFactory` enum. The code for this is: 196 | ```java 197 | EDGE { 198 | @Override 199 | public WebDriver getDriver() { 200 | WebDriver driver = new EdgeDriver(getOptions()); 201 | 202 | driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(config().timeout())); 203 | driver.manage().window().maximize(); 204 | 205 | return driver; 206 | } 207 | 208 | private EdgeOptions getOptions() { 209 | EdgeOptions options = new EdgeOptions(); 210 | 211 | options.setAcceptInsecureCerts(true); 212 | 213 | if (Boolean.TRUE.equals(config().headless())) { 214 | options.addArguments("--headless=new"); 215 | } 216 | 217 | return options; 218 | } 219 | } 220 | ``` 221 | 222 | Now, you can launch all your tests in the `Edge` browser by either setting the property `browser` to `edge` in the [*config.properties*](./src/test/resources/config.properties) file or as a system property via gradle. 223 | 224 | - ### Page Objects and Page Component Objects 225 | The project uses [*Page Objects* and *Page Component Objects*](https://www.selenium.dev/documentation/test_practices/encouraged/page_object_models/) to capture the relevant behaviors of a web page. Check the [*ui*](./src/main/java/io/github/tahanima/ui) package for reference. 226 | 227 | - ### Tests 228 | The project uses *TestNG* as the test runner. Check [this implementation](./src/test/java/io/github/tahanima/e2e/LoginTest.java) for reference. 229 | --------------------------------------------------------------------------------