SlideShare a Scribd company logo
1 of 12
Download to read offline
Mastering Assertions in Automation
Testing, Importance and Best Practices
Introduction:
Welcome aboard to our exploration of automated testing! Here, we’ll talk about assertions,
the trusty guards of reliability and functionality in the testing world. This article digs into
why assertions are so important in automated testing and share some top tips for using them
effectively
We’ll keep things simple as we journey through the world of test automation, showing how
assertions help us check if things are working as they should. Plus, we’ll demystify two
popular frameworks, TestNG and JUnit, which are like our trusty sidekicks in writing solid
automation scripts. So, get ready for a ride where assertions lead us to app quality and
assurance!
What is Assertion in Automated Tests:
Assertions are the unsung heroes of automated testing, ensuring the reliability and
functionality of our digital storefronts much like diligent shopkeepers in an e-commerce
website. They act as validation mechanisms, constantly verifying whether expected
conditions align with reality during test execution. Imagine you’re running an online store
and updating product prices. Assertions are like double-checking that the prices displayed on
the website match the updated values in the database, confirming that customers are charged
correctly for their purchases.
Now, let’s explore the versatility of assertions across different types of automated tests. In
unit tests, assertions validate individual pieces of code, ensuring they perform as expected
within the larger system. During integration tests, assertions verify the smooth
communication between various components of the website, such as the cart, payment
gateway, and inventory management system. In functional automation, assertions validate the
proper functioning of features like search, checkout, and order tracking, ensuring a seamless
user experience. Lastly, in performance testing, assertions monitor website response times
and server resource usage, alerting us to any performance bottlenecks that may impact user
satisfaction.
In summary, assertions are indispensable tools across the diverse landscape of automated
testing, providing reassurance that our e-commerce websites function flawlessly and deliver a
smooth shopping experience to customers
Top 15 Assertions in TestNG with Scenarios, Code Examples, and Usage in
Automation
1. assertEquals
This assertion verifies if two values are equal.
Usage with Automation:
Asserts the title of the web page after successful login
Code Example:
assertEquals(actualTitle, expectedTitle);
2. assertNotEquals
This assertion validates that two values are not equal.
Usage with Automation:
Asserts that the registration fails for an existing username.
Code Example:
assertNotEquals(actualUsername, existingUsername);
3. assertTrue
Verifies if a condition is true.
Usage with Selenium:
Asserts that a button is enabled on the web page.
Code Example:
assertTrue(button.isEnabled());
4. assertFalse
Validates if a condition is false.
Usage with Selenium:
Asserts that an error message is not displayed
Code Example:
assertFalse(errorMessage.isDisplayed());
5. assertNull
It checks if an object reference is null.
Usage with Selenium:
Asserts that no search results are displayed.
Code Example:
assertNull(searchResult);
6. assertNotNull
Ensures that an object reference is not null.
Usage with Selenium:
Asserts that product details are not null.
Code Example:
assertNotNull(productDetails);
7. assertSame
Verifies if two object references point to the same object.
Usage with Selenium:
Asserts that the object reference is the same.
Code Example:
assertSame(actualObject, cachedObject);
8. assertNotSame
Validates that two object references do not point to the same object.
Usage in Automation:
Asserts that a new instance is created.
Code Example:
assertNotSame(actualObject, newObject);
9. assertArrayEquals
Compare two arrays to check if they are equal.
Usage with Selenium:
Asserts the order of elements in a dropdown list.
Code Example:
assertArrayEquals(expectedArray, actualArray);
10. assertThat
Provides more flexibility and readability in assertions using Hamcrest matchers.
Usage with Selenium:
Asserts the presence of an element in a table.
Code Example:
assertThat(listOfElements, hasItem(expectedElement));
11. assertThrows
Verifies if a specific exception is thrown by a method.
Usage with Selenium:
Asserts that an exception is thrown for invalid input.
Code Example:
assertThrows(Exception.class, () -> methodUnderTest());
12. assertTimeout
Ensures that the execution of a method does not exceed a specified timeout.
Usage with Selenium:
Asserts the response time of a web page load.
Code Example:
assertTimeout(Duration.ofMillis(timeout), () -> methodUnderTest());
13. assertAll
Groups multiple assertions and reports all failures together.
Usage with Selenium:
Asserts multiple elements on a web page.
Code Example:
assertAll(“Description”, () -> assertEquals(actual, expected), () -> assertTrue(condition));
14. fail
Explicitly fails a test with a custom message.
Code Example:
fail(“Test failed due to invalid data.”);
Usage with Selenium:
Forcing a test to fail if a critical element is not found.
15. assertThatCode
Executes a block of code and allows assertions to be made.
Usage with Selenium:
Asserts that a piece of JavaScript code executes without errors.
Code Example:
assertThatCode(() -> methodUnderTest()).doesNotThrowAnyException();
Soft Assert vs Hard Assert:
Soft Assert allows the execution of test methods to continue even after an assertion failure,
reporting all failures at the end of the test. On the other hand, Hard Assert immediately stops
test execution upon the first assertion failure. Soft Assert comes in handy when you need to
carry out multiple validations within a single test method without halting the entire test
prematurely.
Soft Assert Example:
public class SOftAssertExample {
public static void main(String[] args) {
// Set Chrome driver path
System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Initialize ChromeDriver
WebDriver driver = new ChromeDriver();
// Launch the website
driver.get(“https://www.google.com”);
// Initialize SoftAssert
SoftAssert softAssert = new SoftAssert();
// Perform soft assertions
softAssert.assertEquals(driver.getTitle(), “Example Domain”);
softAssert.assertTrue(driver.getCurrentUrl().contains(“example.com”));
softAssert.assertTrue(driver.getPageSource().contains(“Example”));
// Perform additional actions
// Assert all soft assertions
softAssert.assertAll();
// Close the browser
driver.quit();
}
}
Hard Assert Example:
public class HardAssertExample {
public static void main(String[] args) {
// Set Chrome driver path
System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Initialize ChromeDriver
WebDriver driver = new ChromeDriver();
// Launch the website
driver.get(“https://www.example.com”);
// Perform hard assertions
Assert.assertEquals(driver.getTitle(), “Example Domain”);
Assert.assertTrue(driver.getCurrentUrl().contains(“example.com”));
Assert.assertTrue(driver.getPageSource().contains(“Example”));
// Perform additional actions
// Close the browser
driver.quit();
}
}
In the Soft Assert example, all assertions are executed, and any failures are recorded but do
not stop the execution of the test. The assertAll() method is called at the end to mark all soft
assertions and report any failures.
In the Hard Assert example, assertions are executed one by one, and if any assertion fails, it
immediately stops the test execution.
Best Practices for Assertions in Test Automation:
Use Descriptive Messages:
Provide clear and meaningful messages for each assertion to make debugging easier.
Example:
@Test
public void verifyLoginErrorMessage() {
LoginPage loginPage = new LoginPage(driver);
loginPage.login(“invalidUsername”, “invalidPassword”);
String actualErrorMessage = loginPage.getErrorMessage();
String expectedErrorMessage = “Invalid username or password”;
Assert.assertEquals(actualErrorMessage, expectedErrorMessage, “Incorrect error message
displayed after login failure.”);
}
Keep Assertions Atomic:
Avoid adding multiple verifications within a single assertion. Each assertion should verify
one specific condition.
Example:
@Test
public void verifyUserDetails() {
UserPage userPage = new UserPage(driver);
User userDetails = userPage.getUserDetails();
Assert.assertNotNull(userDetails, “User details not found.”);
Assert.assertNotNull(userDetails.getUsername(), “Username not found.”);
Assert.assertNotNull(userDetails.getEmail(), “Email not found.”);
}
Use Explicit Wait:
Ensure that elements are present and ready for assertion using explicit wait conditions before
performing assertions on them.
Example:
@Test
public void verifyElementVisibility() {
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement submitButton =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“submit”)));
Assert.assertTrue(submitButton.isDisplayed(), “Submit button not visible.”);
}
Also Avoid Thread.sleep() to wait for elements before assertions. Instead, use explicit waits
to wait for specific conditions.
Verify Expected and Actual Values:
Always verify both expected and actual values in assertions to ensure accuracy.
Example:
@Test
public void verifyProductPrice() {
ProductPage productPage = new ProductPage(driver);
double actualPrice = productPage.getProductPrice();
double expectedPrice = 99.99;
Assert.assertEquals(actualPrice, expectedPrice, 0.01, “Incorrect product price displayed.”);
}
Use Appropriate Assertion Methods:
Choose the appropriate assertion methods based on the type of verification required (e.g.,
assertEquals(), assertTrue(), assertNotNull()).
Example:
@Test
public void verifyElementVisibility() {
WebElement submitButton = driver.findElement(By.id(“submit”));
Assert.assertTrue(submitButton.isDisplayed(), “Submit button not visible.”);
}
Efficient Exception Handling:
Use try-catch blocks to handle exceptions and provide meaningful error messages in case of
assertion failures.
Example:
public void verifyElementPresence() {
try {
WebElement logo = driver.findElement(By.id(“logo”));
Assert.assertNotNull(logo, “Logo element is NOT found”);
} catch (NoSuchElementException e) {
Assert.fail(“Logo element is NOT found.”);
}
}
Conclusion
In conclusion, assertions are super important in test automation using tools like Selenium and
Rest Assured. They act as the quality gates of our test scripts, making sure that the app
behaves as it should and all the expected values are validated with actual results. Becoming
proficient in assertions within automated testing is vital for guaranteeing the precision and
dependability of test outcomes. By grasping the significance of assertions and adhering to
recommended practices, testers can develop resilient and efficient automated test suites,
ultimately resulting in heightened app quality and broader test coverage.
Running tests without assertions is like walking blindfolded—you’re unsure if you’re
heading in the right direction. But with assertions, you gain clarity. You can confidently
affirm, “Yes, the app is functioning as intended.” Therefore, in the realm of test automation,
assertions are indispensable companions. They give meaning to our tests, ensuring their
effectiveness. So, if you’re venturing into test automation, embrace assertions—they’re the
true MVPs of testing.

More Related Content

Similar to Mastering Assertions in Automation Testing, Importance and Best Practices.pdf

Sample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoSample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoTomek Kaczanowski
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnitAktuğ Urun
 
10 Principles of Apex Testing
10 Principles of Apex Testing10 Principles of Apex Testing
10 Principles of Apex TestingKevin Poorman
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Testing Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksTesting Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksŁukasz Morawski
 
Essential information to be included in test cases
Essential information to be included in test casesEssential information to be included in test cases
Essential information to be included in test cases99tests
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialAnup Singh
 
Selenium
SeleniumSelenium
Seleniumnil65
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best PracticesJitendra Zaa
 
Software Testing
Software TestingSoftware Testing
Software TestingAdroitLogic
 
Practical Test Automation Deep Dive
Practical Test Automation Deep DivePractical Test Automation Deep Dive
Practical Test Automation Deep DiveAlan Richardson
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration TestingPaul Churchward
 

Similar to Mastering Assertions in Automation Testing, Importance and Best Practices.pdf (20)

Sample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoSample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and Mockito
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
Junit
JunitJunit
Junit
 
10 Principles of Apex Testing
10 Principles of Apex Testing10 Principles of Apex Testing
10 Principles of Apex Testing
 
Chapter 9
Chapter 9Chapter 9
Chapter 9
 
2310 b 07
2310 b 072310 b 07
2310 b 07
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Testing Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksTesting Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation Frameworks
 
Essential information to be included in test cases
Essential information to be included in test casesEssential information to be included in test cases
Essential information to be included in test cases
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Selenium
SeleniumSelenium
Selenium
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Wheels
WheelsWheels
Wheels
 
Practical Test Automation Deep Dive
Practical Test Automation Deep DivePractical Test Automation Deep Dive
Practical Test Automation Deep Dive
 
Clean tests good tests
Clean tests   good testsClean tests   good tests
Clean tests good tests
 
OLT open script
OLT open script OLT open script
OLT open script
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration Testing
 
Test automation
Test  automationTest  automation
Test automation
 

More from pcloudy2

A Guide to build Continuous Testing infra for Mobile Apps at Scale.pdf
A Guide to build Continuous Testing infra for Mobile Apps at Scale.pdfA Guide to build Continuous Testing infra for Mobile Apps at Scale.pdf
A Guide to build Continuous Testing infra for Mobile Apps at Scale.pdfpcloudy2
 
How Does No Code Testing Work........pdf
How Does No Code Testing Work........pdfHow Does No Code Testing Work........pdf
How Does No Code Testing Work........pdfpcloudy2
 
Automation Tool Evaluation............pdf
Automation Tool Evaluation............pdfAutomation Tool Evaluation............pdf
Automation Tool Evaluation............pdfpcloudy2
 
Basics of Scriptless Automation for Web and Mobile Apps (1).pdf
Basics of Scriptless Automation for Web and Mobile Apps (1).pdfBasics of Scriptless Automation for Web and Mobile Apps (1).pdf
Basics of Scriptless Automation for Web and Mobile Apps (1).pdfpcloudy2
 
Pcloudy Unveils a New Platform for a Unified App Testing Experience.pdf
Pcloudy Unveils a New Platform for a Unified App Testing Experience.pdfPcloudy Unveils a New Platform for a Unified App Testing Experience.pdf
Pcloudy Unveils a New Platform for a Unified App Testing Experience.pdfpcloudy2
 
How To Get Started With API Testing In Your Organization.pdf
How To Get Started With API Testing In Your Organization.pdfHow To Get Started With API Testing In Your Organization.pdf
How To Get Started With API Testing In Your Organization.pdfpcloudy2
 
Accessibility Testing for Web and Mobile Apps A Complete Guide.pdf
Accessibility Testing for Web and Mobile Apps A Complete Guide.pdfAccessibility Testing for Web and Mobile Apps A Complete Guide.pdf
Accessibility Testing for Web and Mobile Apps A Complete Guide.pdfpcloudy2
 
How to use selenium locators effectively for web automation.pdf
How to use selenium locators effectively for web automation.pdfHow to use selenium locators effectively for web automation.pdf
How to use selenium locators effectively for web automation.pdfpcloudy2
 
How to use Selenium Grid for Multi-Browser Testing.pdf
How to use Selenium Grid for Multi-Browser Testing.pdfHow to use Selenium Grid for Multi-Browser Testing.pdf
How to use Selenium Grid for Multi-Browser Testing.pdfpcloudy2
 
How to maintain and update automation scripts with frequent app changes.pdf
How to maintain and update automation scripts with frequent app changes.pdfHow to maintain and update automation scripts with frequent app changes.pdf
How to maintain and update automation scripts with frequent app changes.pdfpcloudy2
 
How to Ensure Compatibility Across Different Browsers and Operating Systems i...
How to Ensure Compatibility Across Different Browsers and Operating Systems i...How to Ensure Compatibility Across Different Browsers and Operating Systems i...
How to Ensure Compatibility Across Different Browsers and Operating Systems i...pcloudy2
 
Discover the Top 23 CSS Frameworks for 2023.pdf
Discover the Top 23 CSS Frameworks for 2023.pdfDiscover the Top 23 CSS Frameworks for 2023.pdf
Discover the Top 23 CSS Frameworks for 2023.pdfpcloudy2
 
Enhancing Continuous Integration with pCloudy’s GitLab CI Integration.pdf
Enhancing Continuous Integration with pCloudy’s GitLab CI Integration.pdfEnhancing Continuous Integration with pCloudy’s GitLab CI Integration.pdf
Enhancing Continuous Integration with pCloudy’s GitLab CI Integration.pdfpcloudy2
 
Mobile app performance testing on different devices and operating systems.pdf
Mobile app performance testing on different devices and operating systems.pdfMobile app performance testing on different devices and operating systems.pdf
Mobile app performance testing on different devices and operating systems.pdfpcloudy2
 
Top Automated UI Testing Tools 2023.pdf
Top Automated UI Testing Tools 2023.pdfTop Automated UI Testing Tools 2023.pdf
Top Automated UI Testing Tools 2023.pdfpcloudy2
 
What is Cloud Testing Everything you need to know.pdf
What is Cloud Testing Everything you need to know.pdfWhat is Cloud Testing Everything you need to know.pdf
What is Cloud Testing Everything you need to know.pdfpcloudy2
 

More from pcloudy2 (16)

A Guide to build Continuous Testing infra for Mobile Apps at Scale.pdf
A Guide to build Continuous Testing infra for Mobile Apps at Scale.pdfA Guide to build Continuous Testing infra for Mobile Apps at Scale.pdf
A Guide to build Continuous Testing infra for Mobile Apps at Scale.pdf
 
How Does No Code Testing Work........pdf
How Does No Code Testing Work........pdfHow Does No Code Testing Work........pdf
How Does No Code Testing Work........pdf
 
Automation Tool Evaluation............pdf
Automation Tool Evaluation............pdfAutomation Tool Evaluation............pdf
Automation Tool Evaluation............pdf
 
Basics of Scriptless Automation for Web and Mobile Apps (1).pdf
Basics of Scriptless Automation for Web and Mobile Apps (1).pdfBasics of Scriptless Automation for Web and Mobile Apps (1).pdf
Basics of Scriptless Automation for Web and Mobile Apps (1).pdf
 
Pcloudy Unveils a New Platform for a Unified App Testing Experience.pdf
Pcloudy Unveils a New Platform for a Unified App Testing Experience.pdfPcloudy Unveils a New Platform for a Unified App Testing Experience.pdf
Pcloudy Unveils a New Platform for a Unified App Testing Experience.pdf
 
How To Get Started With API Testing In Your Organization.pdf
How To Get Started With API Testing In Your Organization.pdfHow To Get Started With API Testing In Your Organization.pdf
How To Get Started With API Testing In Your Organization.pdf
 
Accessibility Testing for Web and Mobile Apps A Complete Guide.pdf
Accessibility Testing for Web and Mobile Apps A Complete Guide.pdfAccessibility Testing for Web and Mobile Apps A Complete Guide.pdf
Accessibility Testing for Web and Mobile Apps A Complete Guide.pdf
 
How to use selenium locators effectively for web automation.pdf
How to use selenium locators effectively for web automation.pdfHow to use selenium locators effectively for web automation.pdf
How to use selenium locators effectively for web automation.pdf
 
How to use Selenium Grid for Multi-Browser Testing.pdf
How to use Selenium Grid for Multi-Browser Testing.pdfHow to use Selenium Grid for Multi-Browser Testing.pdf
How to use Selenium Grid for Multi-Browser Testing.pdf
 
How to maintain and update automation scripts with frequent app changes.pdf
How to maintain and update automation scripts with frequent app changes.pdfHow to maintain and update automation scripts with frequent app changes.pdf
How to maintain and update automation scripts with frequent app changes.pdf
 
How to Ensure Compatibility Across Different Browsers and Operating Systems i...
How to Ensure Compatibility Across Different Browsers and Operating Systems i...How to Ensure Compatibility Across Different Browsers and Operating Systems i...
How to Ensure Compatibility Across Different Browsers and Operating Systems i...
 
Discover the Top 23 CSS Frameworks for 2023.pdf
Discover the Top 23 CSS Frameworks for 2023.pdfDiscover the Top 23 CSS Frameworks for 2023.pdf
Discover the Top 23 CSS Frameworks for 2023.pdf
 
Enhancing Continuous Integration with pCloudy’s GitLab CI Integration.pdf
Enhancing Continuous Integration with pCloudy’s GitLab CI Integration.pdfEnhancing Continuous Integration with pCloudy’s GitLab CI Integration.pdf
Enhancing Continuous Integration with pCloudy’s GitLab CI Integration.pdf
 
Mobile app performance testing on different devices and operating systems.pdf
Mobile app performance testing on different devices and operating systems.pdfMobile app performance testing on different devices and operating systems.pdf
Mobile app performance testing on different devices and operating systems.pdf
 
Top Automated UI Testing Tools 2023.pdf
Top Automated UI Testing Tools 2023.pdfTop Automated UI Testing Tools 2023.pdf
Top Automated UI Testing Tools 2023.pdf
 
What is Cloud Testing Everything you need to know.pdf
What is Cloud Testing Everything you need to know.pdfWhat is Cloud Testing Everything you need to know.pdf
What is Cloud Testing Everything you need to know.pdf
 

Recently uploaded

Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...lizamodels9
 
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service DewasVip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewasmakika9823
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechNewman George Leech
 
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...lizamodels9
 
rishikeshgirls.in- Rishikesh call girl.pdf
rishikeshgirls.in- Rishikesh call girl.pdfrishikeshgirls.in- Rishikesh call girl.pdf
rishikeshgirls.in- Rishikesh call girl.pdfmuskan1121w
 
Call Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any TimeCall Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any Timedelhimodelshub1
 
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfCatalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfOrient Homes
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncrdollysharma2066
 
Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdfOrient Homes
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis UsageNeil Kimberley
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst SummitHolger Mueller
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth MarketingShawn Pang
 
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | DelhiFULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | DelhiMalviyaNagarCallGirl
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCRsoniya singh
 
Case study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailCase study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailAriel592675
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,noida100girls
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfpollardmorgan
 

Recently uploaded (20)

Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
 
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCREnjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
 
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service DewasVip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
Vip Dewas Call Girls #9907093804 Contact Number Escorts Service Dewas
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman Leech
 
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
 
rishikeshgirls.in- Rishikesh call girl.pdf
rishikeshgirls.in- Rishikesh call girl.pdfrishikeshgirls.in- Rishikesh call girl.pdf
rishikeshgirls.in- Rishikesh call girl.pdf
 
Call Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any TimeCall Girls Miyapur 7001305949 all area service COD available Any Time
Call Girls Miyapur 7001305949 all area service COD available Any Time
 
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfCatalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
 
KestrelPro Flyer Japan IT Week 2024 (English)
KestrelPro Flyer Japan IT Week 2024 (English)KestrelPro Flyer Japan IT Week 2024 (English)
KestrelPro Flyer Japan IT Week 2024 (English)
 
Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdf
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst Summit
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
 
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | DelhiFULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR
 
Case study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailCase study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detail
 
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
 

Mastering Assertions in Automation Testing, Importance and Best Practices.pdf

  • 1. Mastering Assertions in Automation Testing, Importance and Best Practices Introduction: Welcome aboard to our exploration of automated testing! Here, we’ll talk about assertions, the trusty guards of reliability and functionality in the testing world. This article digs into why assertions are so important in automated testing and share some top tips for using them effectively We’ll keep things simple as we journey through the world of test automation, showing how assertions help us check if things are working as they should. Plus, we’ll demystify two popular frameworks, TestNG and JUnit, which are like our trusty sidekicks in writing solid automation scripts. So, get ready for a ride where assertions lead us to app quality and assurance! What is Assertion in Automated Tests: Assertions are the unsung heroes of automated testing, ensuring the reliability and functionality of our digital storefronts much like diligent shopkeepers in an e-commerce website. They act as validation mechanisms, constantly verifying whether expected conditions align with reality during test execution. Imagine you’re running an online store and updating product prices. Assertions are like double-checking that the prices displayed on the website match the updated values in the database, confirming that customers are charged correctly for their purchases.
  • 2. Now, let’s explore the versatility of assertions across different types of automated tests. In unit tests, assertions validate individual pieces of code, ensuring they perform as expected within the larger system. During integration tests, assertions verify the smooth communication between various components of the website, such as the cart, payment gateway, and inventory management system. In functional automation, assertions validate the proper functioning of features like search, checkout, and order tracking, ensuring a seamless user experience. Lastly, in performance testing, assertions monitor website response times and server resource usage, alerting us to any performance bottlenecks that may impact user satisfaction. In summary, assertions are indispensable tools across the diverse landscape of automated testing, providing reassurance that our e-commerce websites function flawlessly and deliver a smooth shopping experience to customers Top 15 Assertions in TestNG with Scenarios, Code Examples, and Usage in Automation 1. assertEquals This assertion verifies if two values are equal. Usage with Automation: Asserts the title of the web page after successful login Code Example: assertEquals(actualTitle, expectedTitle); 2. assertNotEquals This assertion validates that two values are not equal. Usage with Automation: Asserts that the registration fails for an existing username.
  • 3. Code Example: assertNotEquals(actualUsername, existingUsername); 3. assertTrue Verifies if a condition is true. Usage with Selenium: Asserts that a button is enabled on the web page. Code Example: assertTrue(button.isEnabled()); 4. assertFalse Validates if a condition is false. Usage with Selenium: Asserts that an error message is not displayed Code Example: assertFalse(errorMessage.isDisplayed()); 5. assertNull It checks if an object reference is null. Usage with Selenium: Asserts that no search results are displayed. Code Example: assertNull(searchResult);
  • 4. 6. assertNotNull Ensures that an object reference is not null. Usage with Selenium: Asserts that product details are not null. Code Example: assertNotNull(productDetails); 7. assertSame Verifies if two object references point to the same object. Usage with Selenium: Asserts that the object reference is the same. Code Example: assertSame(actualObject, cachedObject); 8. assertNotSame Validates that two object references do not point to the same object. Usage in Automation: Asserts that a new instance is created. Code Example: assertNotSame(actualObject, newObject); 9. assertArrayEquals Compare two arrays to check if they are equal.
  • 5. Usage with Selenium: Asserts the order of elements in a dropdown list. Code Example: assertArrayEquals(expectedArray, actualArray); 10. assertThat Provides more flexibility and readability in assertions using Hamcrest matchers. Usage with Selenium: Asserts the presence of an element in a table. Code Example: assertThat(listOfElements, hasItem(expectedElement)); 11. assertThrows Verifies if a specific exception is thrown by a method. Usage with Selenium: Asserts that an exception is thrown for invalid input. Code Example: assertThrows(Exception.class, () -> methodUnderTest()); 12. assertTimeout Ensures that the execution of a method does not exceed a specified timeout. Usage with Selenium:
  • 6. Asserts the response time of a web page load. Code Example: assertTimeout(Duration.ofMillis(timeout), () -> methodUnderTest()); 13. assertAll Groups multiple assertions and reports all failures together. Usage with Selenium: Asserts multiple elements on a web page. Code Example: assertAll(“Description”, () -> assertEquals(actual, expected), () -> assertTrue(condition)); 14. fail Explicitly fails a test with a custom message. Code Example: fail(“Test failed due to invalid data.”); Usage with Selenium: Forcing a test to fail if a critical element is not found. 15. assertThatCode Executes a block of code and allows assertions to be made. Usage with Selenium: Asserts that a piece of JavaScript code executes without errors. Code Example: assertThatCode(() -> methodUnderTest()).doesNotThrowAnyException();
  • 7. Soft Assert vs Hard Assert: Soft Assert allows the execution of test methods to continue even after an assertion failure, reporting all failures at the end of the test. On the other hand, Hard Assert immediately stops test execution upon the first assertion failure. Soft Assert comes in handy when you need to carry out multiple validations within a single test method without halting the entire test prematurely. Soft Assert Example: public class SOftAssertExample { public static void main(String[] args) { // Set Chrome driver path System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”); // Initialize ChromeDriver WebDriver driver = new ChromeDriver(); // Launch the website driver.get(“https://www.google.com”); // Initialize SoftAssert SoftAssert softAssert = new SoftAssert(); // Perform soft assertions softAssert.assertEquals(driver.getTitle(), “Example Domain”); softAssert.assertTrue(driver.getCurrentUrl().contains(“example.com”)); softAssert.assertTrue(driver.getPageSource().contains(“Example”)); // Perform additional actions
  • 8. // Assert all soft assertions softAssert.assertAll(); // Close the browser driver.quit(); } } Hard Assert Example: public class HardAssertExample { public static void main(String[] args) { // Set Chrome driver path System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”); // Initialize ChromeDriver WebDriver driver = new ChromeDriver(); // Launch the website driver.get(“https://www.example.com”); // Perform hard assertions Assert.assertEquals(driver.getTitle(), “Example Domain”); Assert.assertTrue(driver.getCurrentUrl().contains(“example.com”)); Assert.assertTrue(driver.getPageSource().contains(“Example”)); // Perform additional actions // Close the browser driver.quit(); }
  • 9. } In the Soft Assert example, all assertions are executed, and any failures are recorded but do not stop the execution of the test. The assertAll() method is called at the end to mark all soft assertions and report any failures. In the Hard Assert example, assertions are executed one by one, and if any assertion fails, it immediately stops the test execution. Best Practices for Assertions in Test Automation: Use Descriptive Messages: Provide clear and meaningful messages for each assertion to make debugging easier. Example: @Test public void verifyLoginErrorMessage() { LoginPage loginPage = new LoginPage(driver); loginPage.login(“invalidUsername”, “invalidPassword”); String actualErrorMessage = loginPage.getErrorMessage(); String expectedErrorMessage = “Invalid username or password”; Assert.assertEquals(actualErrorMessage, expectedErrorMessage, “Incorrect error message displayed after login failure.”); } Keep Assertions Atomic: Avoid adding multiple verifications within a single assertion. Each assertion should verify one specific condition. Example: @Test
  • 10. public void verifyUserDetails() { UserPage userPage = new UserPage(driver); User userDetails = userPage.getUserDetails(); Assert.assertNotNull(userDetails, “User details not found.”); Assert.assertNotNull(userDetails.getUsername(), “Username not found.”); Assert.assertNotNull(userDetails.getEmail(), “Email not found.”); } Use Explicit Wait: Ensure that elements are present and ready for assertion using explicit wait conditions before performing assertions on them. Example: @Test public void verifyElementVisibility() { WebDriverWait wait = new WebDriverWait(driver, 10); WebElement submitButton = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“submit”))); Assert.assertTrue(submitButton.isDisplayed(), “Submit button not visible.”); } Also Avoid Thread.sleep() to wait for elements before assertions. Instead, use explicit waits to wait for specific conditions. Verify Expected and Actual Values: Always verify both expected and actual values in assertions to ensure accuracy. Example: @Test public void verifyProductPrice() { ProductPage productPage = new ProductPage(driver);
  • 11. double actualPrice = productPage.getProductPrice(); double expectedPrice = 99.99; Assert.assertEquals(actualPrice, expectedPrice, 0.01, “Incorrect product price displayed.”); } Use Appropriate Assertion Methods: Choose the appropriate assertion methods based on the type of verification required (e.g., assertEquals(), assertTrue(), assertNotNull()). Example: @Test public void verifyElementVisibility() { WebElement submitButton = driver.findElement(By.id(“submit”)); Assert.assertTrue(submitButton.isDisplayed(), “Submit button not visible.”); } Efficient Exception Handling: Use try-catch blocks to handle exceptions and provide meaningful error messages in case of assertion failures. Example: public void verifyElementPresence() { try { WebElement logo = driver.findElement(By.id(“logo”)); Assert.assertNotNull(logo, “Logo element is NOT found”); } catch (NoSuchElementException e) { Assert.fail(“Logo element is NOT found.”); } }
  • 12. Conclusion In conclusion, assertions are super important in test automation using tools like Selenium and Rest Assured. They act as the quality gates of our test scripts, making sure that the app behaves as it should and all the expected values are validated with actual results. Becoming proficient in assertions within automated testing is vital for guaranteeing the precision and dependability of test outcomes. By grasping the significance of assertions and adhering to recommended practices, testers can develop resilient and efficient automated test suites, ultimately resulting in heightened app quality and broader test coverage. Running tests without assertions is like walking blindfolded—you’re unsure if you’re heading in the right direction. But with assertions, you gain clarity. You can confidently affirm, “Yes, the app is functioning as intended.” Therefore, in the realm of test automation, assertions are indispensable companions. They give meaning to our tests, ensuring their effectiveness. So, if you’re venturing into test automation, embrace assertions—they’re the true MVPs of testing.