SlideShare a Scribd company logo
Clean Code
In
Test Automation
Presented By
Aditya Kumar Singh
Automation Consultant
(Test Automation Competency)
1. Introduction
2. Clean Testing (Arrange -> Act -> Assert)
3. Characteristics
o Of Good Test Automation Code
o Of Bad Test Automation Code
4. Clean Code Principles in Test Automation
5. Best Practices in Test Automation
Introduction
• Writing clean code is paramount for ensuring that tests
are effective, maintainable, and reliable.
• Clean code in test automation not only facilitates easier
understanding and modification by team members but
also enhances the overall quality and performance of the
test suite.
• The focus will be on differentiating between good and
bad practices in test automation, highlighting the
characteristics of well-written tests and common pitfalls to
avoid.
• By examining these distinctions, we aim to promote best
practices that lead to more efficient and robust automated
testing.
Clean Testing
• Clean Testing is a methodology in test automation that emphasizes writing clear,
readable, and maintainable tests by following a structured pattern known as
Arrange-Act-Assert (AAA).
• This pattern ensures that tests are easy to understand and consistently organized,
which helps in identifying and fixing issues quickly.
• Like clean code, a clean test is simple, direct, and not cluttered with unnecessary
steps or information.
Arrange -> Act -> Assert
• Arrange
o In the Arrange phase, you set up everything needed for the test. This includes:
 Initializing Objects: Create instances of the classes you will test.
 Setting Up Data: Prepare any data or state required for the test.
 Mocking Dependencies: Use mocks or stubs for any external dependencies.
@BeforeClass
public void setUp() {
// Arrange
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com/login");
}
Arrange -> Act -> Assert
• Act
o In the Act phase, you perform the action that you want to test.
o This typically involves calling a method or function.
o Or Simply, Choose an action that will trigger the test result – this could be a click, calling a specific function, or something
else.
@Test
public void testLogin() {
// Arrange
WebElement usernameField = driver.findElement(By.id("username"));
WebElement passwordField = driver.findElement(By.id("password"));
WebElement loginButton = driver.findElement(By.id("loginButton"));
// Act
usernameField.sendKeys("testuser");
passwordField.sendKeys("testpassword");
loginButton.click();
}
Arrange -> Act -> Assert
• Assert
o In the Assert phase, you verify that the outcome is as expected.
o This is where you check the results of the action performed in the Act phase against the expected results.
o Or Assert the result was what was expected.
@Test
public void testLogin() {
// Arrange
WebElement usernameField = driver.findElement(By.id("username"));
WebElement passwordField = driver.findElement(By.id("password"));
WebElement loginButton = driver.findElement(By.id("loginButton"));
// Act
usernameField.sendKeys("testuser");
passwordField.sendKeys("testpassword");
loginButton.click();
// Assert
WebElement welcomeMessage = driver.findElement(By.id("welcomeMessage"));
Assert.assertTrue(welcomeMessage.isDisplayed(), "Login failed: Welcome message is not displayed.");
Assert.assertEquals(welcomeMessage.getText(), "Welcome, testuser!", "Login failed: Incorrect welcome message.");
}
Characteristics Of Good Automation Code
Good automation code is essential for ensuring reliability, efficiency, and maintainability in automated processes. Here are
some key characteristics of well-written automation code:
• Readability
• Clear and Concise: The code should be easy to read and understand.
• Consistent Naming Conventions: Adopting a consistent style for naming variables, functions, and classes.
• Comments: Appropriate comments help others (and your future self) understand the code's functionality and intent.
• Modularity
• Functions and Modules: Breaking down the code into reusable functions and modules makes it easier to manage.
• Single Responsibility: Each function or module should have a single, well-defined responsibility.
• Flexibility and Configurability
• Configurable Parameters: Using configuration files or environment variables allows the code to be easily adapted to different
environments or use cases without modifying the codebase.
• Extensibility: The code should be designed to accommodate future changes or additional features with minimal modifications.
• Error Handling and Logging
• Error Handling: Proper error handling mechanisms should be in place to gracefully handle exceptions and errors without
crashing.
• Logging: Implementing logging helps in debugging and provides insights into the code's execution flow.
Characteristics Of Good Automation Code
• Compliance and Standards
• Adherence to Standards: Following industry standards and best practices for coding ensures that the automation code
is reliable and interoperable.
• Code Reviews: Regular code reviews help identify issues early and improve the overall quality of the code.
• Security
• Secure Practices: Following best security practices, such as avoiding hard-coded credentials and using secure
connections, protects against vulnerabilities.
• Input Validation: Validating inputs ensures that the code handles unexpected or malicious data appropriately.
• Scalability
• Efficient Algorithms: Writing efficient algorithms ensures that the code can handle increasing amounts of data or
complexity without significant performance degradation.
• Parallelization: Where possible, enabling parallel execution of tasks can improve performance.
Characteristics Of Bad Automation Code
Bad automation code can lead to inefficiencies, difficulties in maintenance, and potential failures in automated processes.
Here are some characteristics that typically define poor automation code:
• Poor Readability
• Unclear Naming: Using non-descriptive variable and function names that do not convey their purpose.
• Inconsistent Style: Inconsistent naming conventions and coding styles, leading to confusion and difficulty in following the code.
• Lack of Comments: Absence of comments or documentation, making it difficult to understand the code’s intent and functionality.
• Monolithic Structure
• Lack of Modularity: Writing large, monolithic blocks of code without breaking them down into smaller, reusable functions or
modules.
• Multiple Responsibilities: Functions or modules that handle multiple tasks, making them complex and difficult to understand or
reuse.
• Redundancy
• Code Duplication: Repeating the same code in multiple places instead of abstracting common functionality into reusable
components.
• Weak Error Handling
• No Error Handling: Failing to handle potential errors or exceptions, which can cause the automation to crash unexpectedly.
• Poor Logging: Inadequate or absent logging, making it hard to diagnose issues or understand the code’s execution flow.
Characteristics Of Bad Automation Code
• Non-Adherence to Standards
• Ignoring Best Practices: Not following industry best practices and coding standards, leading to lower quality and less
reliable code.
• No Code Reviews: Skipping code reviews, missing out on opportunities to catch issues early and improve code quality.
• Security Vulnerabilities
• Hardcoded Credentials: Storing sensitive information like credentials directly in the code, which can be a major security
risk.
• Lack of Input Validation: Failing to validate inputs, making the code vulnerable to injection attacks and other security
issues.
• Hardcoding and Inflexibility
• Hardcoded Values: Using hardcoded values for configurations, making the code less flexible and harder to adapt to
different environments.
• Non-Configurable: Lack of configurable parameters, requiring code changes for different use cases or environments.
Clean Code Principles in Test Automation
• Single Responsibility Principle
o This principle states that a class or module should have only one reason to change.
o In test automation, this means that each test case or test suite should focus on testing a single piece of functionality.
o It helps in maintaining the tests, as any change in the feature being tested should only require changes in one place.
Clean Code Principles in Test Automation
• Open/Closed Principle
o The Open/Closed Principle suggests that software entities (classes, functions, etc.) should be open for extension but
closed for modification.
o In test automation, this could mean that your test cases should be designed in a way that allows for easy extension
(adding new test cases) without modifying existing ones.
o This could be achieved through proper abstraction and use of design patterns like Page Object Model.
Clean Code Principles in Test Automation
• FIRST Principle
o FIRST stands for Fast, Isolated/Independent, Repeatable, Self-Validating, and Timely.
 Fast: Tests should execute quickly to provide rapid feedback.
 Isolated/Independent: Tests should not depend on each other. Each test should be able to run independently.
 Repeatable: Tests should produce the same result every time they are run.
 Self-Validating: Tests should have a Boolean output. They should pass or fail clearly.
 Timely: Tests should be written timely, ideally before the code they are testing is implemented, following a test-driven development
(TDD) approach.
Clean Code Principles in Test Automation
• Single Level of Abstraction Principle
o This principle states that there should not be multiple levels of abstraction within a function or method.
o In test automation, this means that test methods should have a single level of abstraction, making them easier to read and
understand.
Clean Code Principles in Test Automation
• Dependency Injection Principle
o This principle promotes injecting dependencies into a class rather than creating them internally.
o In test automation, this allows for easier testing by enabling the injection of mock objects or test doubles to isolate the
component under test.
Best Practices in Test Automation
Descriptive
Naming
Lorem Ipsum is
simply dummy text of
the printing.
Lorem Ipsum is
simply dummy text of
the printing.
Small
And
Focused Tests
Page Object
Model
Parameterized
Values
Assertions
Waits
Logging
And
Reporting
Best Practices in Test Automation
• Use Descriptive Naming
o In test automation, Choose descriptive names for classes, methods, and variables that convey their purpose.
o For Example,
public class LoginPageTest {
@Test
public void loginWithValidCredentials_shouldSucceed() {
// Arrange: Set up the test scenario
WebDriver driver = new ChromeDriver();
LoginPage loginPage = new LoginPage(driver);
// Act: Perform the login operation
loginPage.navigate();
loginPage.login(TestConstants.VALID_USERNAME, TestConstants.VALID_PASSWORD);
// Assert: Verify the expected outcome
assertTrue("Login successful", driver.getTitle().contains("Dashboard"));
// Clean up: Close the browser
driver.quit();
}
}
Best Practices in Test Automation
• Keep Tests Small and Focused
o In test automation, each test should focus on testing a single functionality or scenario.
o For Example,
// Validating the login page
@Test
public void loginWithValidCredentials_shouldSucceed() {
// Arrange: Set up the test scenario
WebDriver driver = new ChromeDriver();
LoginPage loginPage = new LoginPage(driver);
// Act: Perform the login operation
loginPage.navigate();
loginPage.login(TestConstants.VALID_USER, TestConstants.VALID_PASS);
// Assert: Verify the expected outcome
assertTrue("Login successful", driver.getTitle().contains("Dashboard"));
// Clean up: Close the browser
driver.quit();
}
// Validating the home page
@Test
public void navigateToHomePage_afterSuccessfulLogin() {
// Arrange: Set up the test scenario
WebDriver driver = new ChromeDriver();
LoginPage loginPage = new LoginPage(driver);
HomePage homePage = new HomePage(driver);
// Act: Perform the login operation
loginPage.navigate();
loginPage.login(TestConstants.VALID_USER, TestConstants.VALID_PASS);
// Act: Navigate to the home page
homePage.navigateToHomePage();
// Assert: Verify the expected outcome
assertTrue("Home page is displayed", homePage.isHomePageDisplayed());
// Clean up: Close the browser
driver.quit();
}
Best Practices in Test Automation
• Use Page Object Model (POM)
o In test automation, encapsulate web elements and actions into Page Objects to promote reusability and
maintainability.
o For Example, import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
private WebDriver driver;
private By usernameInput = By.id("username");
private By passwordInput = By.id("password");
private By loginButton = By.id("login");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void navigate() {
driver.get(TestConstants.BASE_URL + "/login");
}
public void login(String username, String password) {
driver.findElement(usernameInput).sendKeys(username);
driver.findElement(passwordInput).sendKeys(password);
driver.findElement(loginButton).click();
}
}
Best Practices in Test Automation
• Avoid Hardcoding Values
o In test automation, use configuration files or constants to store test data and configuration settings.
o For Example,
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
private WebDriver driver;
private By usernameInput = By.id("username");
private By passwordInput = By.id("password");
private By loginButton = By.id("login");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void navigate() {
driver.get(TestConstants.BASE_URL + "/login");
}
public void login(String username, String password) {
driver.findElement(usernameInput).sendKeys(username);
driver.findElement(passwordInput).sendKeys(password);
driver.findElement(loginButton).click();
}
}
// Example:
public class TestConstants {
public static final String BASE_URL = "https://example.com";
public static final String USERNAME = "testuser";
public static final String PASSWORD = "password123";
}
Best Practices in Test Automation
• Keep Assertions Clear and Concise
o In test automation, use meaningful messages in assertions to understand failures easily.
o For Example,
@Test
public void loginWithValidCredentials_shouldSucceed() {
// Arrange: Set up the test scenario
WebDriver driver = new ChromeDriver();
LoginPage loginPage = new LoginPage(driver);
HomePage homePage = new HomePage(driver);
// Act: Perform the login operation
loginPage.navigate();
loginPage.login(TestConstants.VALID_USER, TestConstants.VALID_PASS);
// Assert: Verify the expected outcome
assertEquals("The page title should be 'Dashboard' after successful login", "Dashboard", driver.getTitle());
// Clean up: Close the browser
driver.quit();
}
// Example:
assertEquals("Login successful", driver.getTitle());
Best Practices in Test Automation
• Handle Waits Properly
o In test automation, use explicit and implicit waits to handle synchronization issues.
o For Example,
@BeforeMethod
public void setUp() {
// Set up the ChromeDriver path
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Initialize the ChromeDriver
driver = new ChromeDriver();
// Set implicit wait (applies to all elements)
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Initialize WebDriverWait (explicit wait)
wait = new WebDriverWait(driver, 10);
// Navigate to the desired URL
driver.get("https://example.com");
}
// Example:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));
Best Practices in Test Automation
• Parameterize Tests
o In test automation, use parameterization to run tests with different data sets.
o For Example,
@Test(dataProvider = "loginData")
public void loginWithValidCredentials_shouldSucceed(String username, String password) {
// Act: Perform the login operation
loginPage.navigate();
loginPage.login(username, password);
// Assert: Verify the expected outcome
assertEquals(driver.getTitle(), "Dashboard", "The page title should be Dashboard'");
}
@Test(dataProvider = "loginData")
public void navigateToHomePage_afterSuccessfulLogin(String username, String password) {
// Act: Perform the login operation
loginPage.navigate();
loginPage.login(username, password);
// Act: Navigate to the home page
homePage.navigateToHomePage();
// Assert: Verify the expected outcome
assertTrue(homePage.isHomePageDisplayed(), "The home page should be displayed after navigation");
}
// Example:
@DataProvider(name = "loginData")
public Object[][] loginData() {
return new Object[][] {
{"username1", "password1"},
{"username2", "password2"}
};
}
Best Practices in Test Automation
• Implement Logging and Reporting
o In test automation, use logging frameworks like Log4j or SLF4J to log informative messages for debugging.
o Utilize reporting tools like ExtentReports or TestNG reports for generating comprehensive test reports.
o For Example,
@Test(dataProvider = "loginData")
public void loginWithValidCredentials_shouldSucceed(String username, String password) {
test = extent.createTest("loginWithValidCredentials_shouldSucceed with " + username);
logger.info("Starting login test with username: " + username);
test.log(Status.INFO, "Starting login test with username: " + username);
// Act: Perform the login operation
loginPage.navigate();
test.log(Status.INFO, "Navigated to login page");
loginPage.login(username, password);
test.log(Status.INFO, "Performed login with username: " + username);
// Assert: Verify the expected outcome
String expectedTitle = "Dashboard";
String actualTitle = driver.getTitle();
logger.info("Verifying the page title. Expected: " + expectedTitle + ", Actual: " + actualTitle);
test.log(Status.INFO, "Verifying the page title. Expected: " + expectedTitle + ", Actual: " + actualTitle);
}
}
// Example:
Logger logger = Logger.getLogger(LoginPageTest.class.getName());
logger.info("Login test started...");
DEMO
Clean Code in Test Automation  Differentiating Between the Good and the Bad

More Related Content

Similar to Clean Code in Test Automation Differentiating Between the Good and the Bad

Object Oriented Testing(OOT) presentation slides
Object Oriented Testing(OOT) presentation slidesObject Oriented Testing(OOT) presentation slides
Object Oriented Testing(OOT) presentation slides
Punjab University
 
Software engineering Testing technique,test case,test suit design
Software engineering Testing technique,test case,test suit designSoftware engineering Testing technique,test case,test suit design
Software engineering Testing technique,test case,test suit design
Maitree Patel
 
Sqa, test scenarios and test cases
Sqa, test scenarios and test casesSqa, test scenarios and test cases
Sqa, test scenarios and test cases
Confiz
 
Generating Test Cases
Generating Test CasesGenerating Test Cases
Generating Test Cases
VivekRajawat9
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
Sahar Nofal
 
6. oose testing
6. oose testing6. oose testing
6. oose testing
Ashenafi Workie
 
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
AgileNetwork
 
White box testing
White box testingWhite box testing
White box testing
Neethu Tressa
 
Testing Plan
Testing PlanTesting Plan
Testing Plan
Ajeng Savitri
 
Software Test Automation - Best Practices
Software Test Automation - Best PracticesSoftware Test Automation - Best Practices
Software Test Automation - Best Practices
Arul Selvan
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Aleksandar Bozinovski
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
Aleksandar Bozinovski
 
Cypress Best Pratices for Test Automation
Cypress Best Pratices for Test AutomationCypress Best Pratices for Test Automation
Cypress Best Pratices for Test Automation
Knoldus Inc.
 
What is software testing in software engineering?
What is software testing in software engineering?What is software testing in software engineering?
What is software testing in software engineering?
tommychauhan
 
What is Testing in Software Engineering?
What is Testing in Software Engineering?What is Testing in Software Engineering?
What is Testing in Software Engineering?
tommychauhan
 
Unit testing
Unit testingUnit testing
Unit testing
Vinod Wilson
 
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
TEST Huddle
 
Test planning and software's engineering
Test planning and software's engineeringTest planning and software's engineering
Test planning and software's engineering
MansiganeshJawale
 
Test driven development
Test driven developmentTest driven development
Test driven development
namkha87
 
testing
testingtesting
testing
Rashmi Deoli
 

Similar to Clean Code in Test Automation Differentiating Between the Good and the Bad (20)

Object Oriented Testing(OOT) presentation slides
Object Oriented Testing(OOT) presentation slidesObject Oriented Testing(OOT) presentation slides
Object Oriented Testing(OOT) presentation slides
 
Software engineering Testing technique,test case,test suit design
Software engineering Testing technique,test case,test suit designSoftware engineering Testing technique,test case,test suit design
Software engineering Testing technique,test case,test suit design
 
Sqa, test scenarios and test cases
Sqa, test scenarios and test casesSqa, test scenarios and test cases
Sqa, test scenarios and test cases
 
Generating Test Cases
Generating Test CasesGenerating Test Cases
Generating Test Cases
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
6. oose testing
6. oose testing6. oose testing
6. oose testing
 
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...Agile Mumbai 2020 Conference |  How to get the best ROI on Your Test Automati...
Agile Mumbai 2020 Conference | How to get the best ROI on Your Test Automati...
 
White box testing
White box testingWhite box testing
White box testing
 
Testing Plan
Testing PlanTesting Plan
Testing Plan
 
Software Test Automation - Best Practices
Software Test Automation - Best PracticesSoftware Test Automation - Best Practices
Software Test Automation - Best Practices
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
 
Cypress Best Pratices for Test Automation
Cypress Best Pratices for Test AutomationCypress Best Pratices for Test Automation
Cypress Best Pratices for Test Automation
 
What is software testing in software engineering?
What is software testing in software engineering?What is software testing in software engineering?
What is software testing in software engineering?
 
What is Testing in Software Engineering?
What is Testing in Software Engineering?What is Testing in Software Engineering?
What is Testing in Software Engineering?
 
Unit testing
Unit testingUnit testing
Unit testing
 
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
 
Test planning and software's engineering
Test planning and software's engineeringTest planning and software's engineering
Test planning and software's engineering
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
testing
testingtesting
testing
 

More from Knoldus Inc.

Terratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructureTerratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructure
Knoldus Inc.
 
Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)
Knoldus Inc.
 
Secure practices with dot net services.pptx
Secure practices with dot net services.pptxSecure practices with dot net services.pptx
Secure practices with dot net services.pptx
Knoldus Inc.
 
Distributed Cache with dot microservices
Distributed Cache with dot microservicesDistributed Cache with dot microservices
Distributed Cache with dot microservices
Knoldus Inc.
 
Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)
Knoldus Inc.
 
Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
Knoldus Inc.
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
Knoldus Inc.
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
Knoldus Inc.
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
Knoldus Inc.
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
Knoldus Inc.
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
Knoldus Inc.
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
Knoldus Inc.
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
Knoldus Inc.
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
Knoldus Inc.
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
Knoldus Inc.
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
Knoldus Inc.
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Knoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
Knoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
Knoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
Knoldus Inc.
 

More from Knoldus Inc. (20)

Terratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructureTerratest - Automation testing of infrastructure
Terratest - Automation testing of infrastructure
 
Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)Getting Started with Apache Spark (Scala)
Getting Started with Apache Spark (Scala)
 
Secure practices with dot net services.pptx
Secure practices with dot net services.pptxSecure practices with dot net services.pptx
Secure practices with dot net services.pptx
 
Distributed Cache with dot microservices
Distributed Cache with dot microservicesDistributed Cache with dot microservices
Distributed Cache with dot microservices
 
Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)Introduction to gRPC Presentation (Java)
Introduction to gRPC Presentation (Java)
 
Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 

Recently uploaded

みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 

Recently uploaded (20)

みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 

Clean Code in Test Automation Differentiating Between the Good and the Bad

  • 1. Clean Code In Test Automation Presented By Aditya Kumar Singh Automation Consultant (Test Automation Competency)
  • 2. 1. Introduction 2. Clean Testing (Arrange -> Act -> Assert) 3. Characteristics o Of Good Test Automation Code o Of Bad Test Automation Code 4. Clean Code Principles in Test Automation 5. Best Practices in Test Automation
  • 3. Introduction • Writing clean code is paramount for ensuring that tests are effective, maintainable, and reliable. • Clean code in test automation not only facilitates easier understanding and modification by team members but also enhances the overall quality and performance of the test suite. • The focus will be on differentiating between good and bad practices in test automation, highlighting the characteristics of well-written tests and common pitfalls to avoid. • By examining these distinctions, we aim to promote best practices that lead to more efficient and robust automated testing.
  • 4. Clean Testing • Clean Testing is a methodology in test automation that emphasizes writing clear, readable, and maintainable tests by following a structured pattern known as Arrange-Act-Assert (AAA). • This pattern ensures that tests are easy to understand and consistently organized, which helps in identifying and fixing issues quickly. • Like clean code, a clean test is simple, direct, and not cluttered with unnecessary steps or information.
  • 5. Arrange -> Act -> Assert • Arrange o In the Arrange phase, you set up everything needed for the test. This includes:  Initializing Objects: Create instances of the classes you will test.  Setting Up Data: Prepare any data or state required for the test.  Mocking Dependencies: Use mocks or stubs for any external dependencies. @BeforeClass public void setUp() { // Arrange System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://example.com/login"); }
  • 6. Arrange -> Act -> Assert • Act o In the Act phase, you perform the action that you want to test. o This typically involves calling a method or function. o Or Simply, Choose an action that will trigger the test result – this could be a click, calling a specific function, or something else. @Test public void testLogin() { // Arrange WebElement usernameField = driver.findElement(By.id("username")); WebElement passwordField = driver.findElement(By.id("password")); WebElement loginButton = driver.findElement(By.id("loginButton")); // Act usernameField.sendKeys("testuser"); passwordField.sendKeys("testpassword"); loginButton.click(); }
  • 7. Arrange -> Act -> Assert • Assert o In the Assert phase, you verify that the outcome is as expected. o This is where you check the results of the action performed in the Act phase against the expected results. o Or Assert the result was what was expected. @Test public void testLogin() { // Arrange WebElement usernameField = driver.findElement(By.id("username")); WebElement passwordField = driver.findElement(By.id("password")); WebElement loginButton = driver.findElement(By.id("loginButton")); // Act usernameField.sendKeys("testuser"); passwordField.sendKeys("testpassword"); loginButton.click(); // Assert WebElement welcomeMessage = driver.findElement(By.id("welcomeMessage")); Assert.assertTrue(welcomeMessage.isDisplayed(), "Login failed: Welcome message is not displayed."); Assert.assertEquals(welcomeMessage.getText(), "Welcome, testuser!", "Login failed: Incorrect welcome message."); }
  • 8. Characteristics Of Good Automation Code Good automation code is essential for ensuring reliability, efficiency, and maintainability in automated processes. Here are some key characteristics of well-written automation code: • Readability • Clear and Concise: The code should be easy to read and understand. • Consistent Naming Conventions: Adopting a consistent style for naming variables, functions, and classes. • Comments: Appropriate comments help others (and your future self) understand the code's functionality and intent. • Modularity • Functions and Modules: Breaking down the code into reusable functions and modules makes it easier to manage. • Single Responsibility: Each function or module should have a single, well-defined responsibility. • Flexibility and Configurability • Configurable Parameters: Using configuration files or environment variables allows the code to be easily adapted to different environments or use cases without modifying the codebase. • Extensibility: The code should be designed to accommodate future changes or additional features with minimal modifications. • Error Handling and Logging • Error Handling: Proper error handling mechanisms should be in place to gracefully handle exceptions and errors without crashing. • Logging: Implementing logging helps in debugging and provides insights into the code's execution flow.
  • 9. Characteristics Of Good Automation Code • Compliance and Standards • Adherence to Standards: Following industry standards and best practices for coding ensures that the automation code is reliable and interoperable. • Code Reviews: Regular code reviews help identify issues early and improve the overall quality of the code. • Security • Secure Practices: Following best security practices, such as avoiding hard-coded credentials and using secure connections, protects against vulnerabilities. • Input Validation: Validating inputs ensures that the code handles unexpected or malicious data appropriately. • Scalability • Efficient Algorithms: Writing efficient algorithms ensures that the code can handle increasing amounts of data or complexity without significant performance degradation. • Parallelization: Where possible, enabling parallel execution of tasks can improve performance.
  • 10. Characteristics Of Bad Automation Code Bad automation code can lead to inefficiencies, difficulties in maintenance, and potential failures in automated processes. Here are some characteristics that typically define poor automation code: • Poor Readability • Unclear Naming: Using non-descriptive variable and function names that do not convey their purpose. • Inconsistent Style: Inconsistent naming conventions and coding styles, leading to confusion and difficulty in following the code. • Lack of Comments: Absence of comments or documentation, making it difficult to understand the code’s intent and functionality. • Monolithic Structure • Lack of Modularity: Writing large, monolithic blocks of code without breaking them down into smaller, reusable functions or modules. • Multiple Responsibilities: Functions or modules that handle multiple tasks, making them complex and difficult to understand or reuse. • Redundancy • Code Duplication: Repeating the same code in multiple places instead of abstracting common functionality into reusable components. • Weak Error Handling • No Error Handling: Failing to handle potential errors or exceptions, which can cause the automation to crash unexpectedly. • Poor Logging: Inadequate or absent logging, making it hard to diagnose issues or understand the code’s execution flow.
  • 11. Characteristics Of Bad Automation Code • Non-Adherence to Standards • Ignoring Best Practices: Not following industry best practices and coding standards, leading to lower quality and less reliable code. • No Code Reviews: Skipping code reviews, missing out on opportunities to catch issues early and improve code quality. • Security Vulnerabilities • Hardcoded Credentials: Storing sensitive information like credentials directly in the code, which can be a major security risk. • Lack of Input Validation: Failing to validate inputs, making the code vulnerable to injection attacks and other security issues. • Hardcoding and Inflexibility • Hardcoded Values: Using hardcoded values for configurations, making the code less flexible and harder to adapt to different environments. • Non-Configurable: Lack of configurable parameters, requiring code changes for different use cases or environments.
  • 12. Clean Code Principles in Test Automation • Single Responsibility Principle o This principle states that a class or module should have only one reason to change. o In test automation, this means that each test case or test suite should focus on testing a single piece of functionality. o It helps in maintaining the tests, as any change in the feature being tested should only require changes in one place.
  • 13. Clean Code Principles in Test Automation • Open/Closed Principle o The Open/Closed Principle suggests that software entities (classes, functions, etc.) should be open for extension but closed for modification. o In test automation, this could mean that your test cases should be designed in a way that allows for easy extension (adding new test cases) without modifying existing ones. o This could be achieved through proper abstraction and use of design patterns like Page Object Model.
  • 14. Clean Code Principles in Test Automation • FIRST Principle o FIRST stands for Fast, Isolated/Independent, Repeatable, Self-Validating, and Timely.  Fast: Tests should execute quickly to provide rapid feedback.  Isolated/Independent: Tests should not depend on each other. Each test should be able to run independently.  Repeatable: Tests should produce the same result every time they are run.  Self-Validating: Tests should have a Boolean output. They should pass or fail clearly.  Timely: Tests should be written timely, ideally before the code they are testing is implemented, following a test-driven development (TDD) approach.
  • 15. Clean Code Principles in Test Automation • Single Level of Abstraction Principle o This principle states that there should not be multiple levels of abstraction within a function or method. o In test automation, this means that test methods should have a single level of abstraction, making them easier to read and understand.
  • 16. Clean Code Principles in Test Automation • Dependency Injection Principle o This principle promotes injecting dependencies into a class rather than creating them internally. o In test automation, this allows for easier testing by enabling the injection of mock objects or test doubles to isolate the component under test.
  • 17. Best Practices in Test Automation Descriptive Naming Lorem Ipsum is simply dummy text of the printing. Lorem Ipsum is simply dummy text of the printing. Small And Focused Tests Page Object Model Parameterized Values Assertions Waits Logging And Reporting
  • 18. Best Practices in Test Automation • Use Descriptive Naming o In test automation, Choose descriptive names for classes, methods, and variables that convey their purpose. o For Example, public class LoginPageTest { @Test public void loginWithValidCredentials_shouldSucceed() { // Arrange: Set up the test scenario WebDriver driver = new ChromeDriver(); LoginPage loginPage = new LoginPage(driver); // Act: Perform the login operation loginPage.navigate(); loginPage.login(TestConstants.VALID_USERNAME, TestConstants.VALID_PASSWORD); // Assert: Verify the expected outcome assertTrue("Login successful", driver.getTitle().contains("Dashboard")); // Clean up: Close the browser driver.quit(); } }
  • 19. Best Practices in Test Automation • Keep Tests Small and Focused o In test automation, each test should focus on testing a single functionality or scenario. o For Example, // Validating the login page @Test public void loginWithValidCredentials_shouldSucceed() { // Arrange: Set up the test scenario WebDriver driver = new ChromeDriver(); LoginPage loginPage = new LoginPage(driver); // Act: Perform the login operation loginPage.navigate(); loginPage.login(TestConstants.VALID_USER, TestConstants.VALID_PASS); // Assert: Verify the expected outcome assertTrue("Login successful", driver.getTitle().contains("Dashboard")); // Clean up: Close the browser driver.quit(); } // Validating the home page @Test public void navigateToHomePage_afterSuccessfulLogin() { // Arrange: Set up the test scenario WebDriver driver = new ChromeDriver(); LoginPage loginPage = new LoginPage(driver); HomePage homePage = new HomePage(driver); // Act: Perform the login operation loginPage.navigate(); loginPage.login(TestConstants.VALID_USER, TestConstants.VALID_PASS); // Act: Navigate to the home page homePage.navigateToHomePage(); // Assert: Verify the expected outcome assertTrue("Home page is displayed", homePage.isHomePageDisplayed()); // Clean up: Close the browser driver.quit(); }
  • 20. Best Practices in Test Automation • Use Page Object Model (POM) o In test automation, encapsulate web elements and actions into Page Objects to promote reusability and maintainability. o For Example, import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class LoginPage { private WebDriver driver; private By usernameInput = By.id("username"); private By passwordInput = By.id("password"); private By loginButton = By.id("login"); public LoginPage(WebDriver driver) { this.driver = driver; } public void navigate() { driver.get(TestConstants.BASE_URL + "/login"); } public void login(String username, String password) { driver.findElement(usernameInput).sendKeys(username); driver.findElement(passwordInput).sendKeys(password); driver.findElement(loginButton).click(); } }
  • 21. Best Practices in Test Automation • Avoid Hardcoding Values o In test automation, use configuration files or constants to store test data and configuration settings. o For Example, import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class LoginPage { private WebDriver driver; private By usernameInput = By.id("username"); private By passwordInput = By.id("password"); private By loginButton = By.id("login"); public LoginPage(WebDriver driver) { this.driver = driver; } public void navigate() { driver.get(TestConstants.BASE_URL + "/login"); } public void login(String username, String password) { driver.findElement(usernameInput).sendKeys(username); driver.findElement(passwordInput).sendKeys(password); driver.findElement(loginButton).click(); } } // Example: public class TestConstants { public static final String BASE_URL = "https://example.com"; public static final String USERNAME = "testuser"; public static final String PASSWORD = "password123"; }
  • 22. Best Practices in Test Automation • Keep Assertions Clear and Concise o In test automation, use meaningful messages in assertions to understand failures easily. o For Example, @Test public void loginWithValidCredentials_shouldSucceed() { // Arrange: Set up the test scenario WebDriver driver = new ChromeDriver(); LoginPage loginPage = new LoginPage(driver); HomePage homePage = new HomePage(driver); // Act: Perform the login operation loginPage.navigate(); loginPage.login(TestConstants.VALID_USER, TestConstants.VALID_PASS); // Assert: Verify the expected outcome assertEquals("The page title should be 'Dashboard' after successful login", "Dashboard", driver.getTitle()); // Clean up: Close the browser driver.quit(); } // Example: assertEquals("Login successful", driver.getTitle());
  • 23. Best Practices in Test Automation • Handle Waits Properly o In test automation, use explicit and implicit waits to handle synchronization issues. o For Example, @BeforeMethod public void setUp() { // Set up the ChromeDriver path System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); // Initialize the ChromeDriver driver = new ChromeDriver(); // Set implicit wait (applies to all elements) driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Initialize WebDriverWait (explicit wait) wait = new WebDriverWait(driver, 10); // Navigate to the desired URL driver.get("https://example.com"); } // Example: WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));
  • 24. Best Practices in Test Automation • Parameterize Tests o In test automation, use parameterization to run tests with different data sets. o For Example, @Test(dataProvider = "loginData") public void loginWithValidCredentials_shouldSucceed(String username, String password) { // Act: Perform the login operation loginPage.navigate(); loginPage.login(username, password); // Assert: Verify the expected outcome assertEquals(driver.getTitle(), "Dashboard", "The page title should be Dashboard'"); } @Test(dataProvider = "loginData") public void navigateToHomePage_afterSuccessfulLogin(String username, String password) { // Act: Perform the login operation loginPage.navigate(); loginPage.login(username, password); // Act: Navigate to the home page homePage.navigateToHomePage(); // Assert: Verify the expected outcome assertTrue(homePage.isHomePageDisplayed(), "The home page should be displayed after navigation"); } // Example: @DataProvider(name = "loginData") public Object[][] loginData() { return new Object[][] { {"username1", "password1"}, {"username2", "password2"} }; }
  • 25. Best Practices in Test Automation • Implement Logging and Reporting o In test automation, use logging frameworks like Log4j or SLF4J to log informative messages for debugging. o Utilize reporting tools like ExtentReports or TestNG reports for generating comprehensive test reports. o For Example, @Test(dataProvider = "loginData") public void loginWithValidCredentials_shouldSucceed(String username, String password) { test = extent.createTest("loginWithValidCredentials_shouldSucceed with " + username); logger.info("Starting login test with username: " + username); test.log(Status.INFO, "Starting login test with username: " + username); // Act: Perform the login operation loginPage.navigate(); test.log(Status.INFO, "Navigated to login page"); loginPage.login(username, password); test.log(Status.INFO, "Performed login with username: " + username); // Assert: Verify the expected outcome String expectedTitle = "Dashboard"; String actualTitle = driver.getTitle(); logger.info("Verifying the page title. Expected: " + expectedTitle + ", Actual: " + actualTitle); test.log(Status.INFO, "Verifying the page title. Expected: " + expectedTitle + ", Actual: " + actualTitle); } } // Example: Logger logger = Logger.getLogger(LoginPageTest.class.getName()); logger.info("Login test started...");
  • 26. DEMO