FrameWork Features:
1)reusability of the Code
2)Maintenance of code is very eay
3)It provides the Reports
4)It provides the logs and screenshots
5)any non technical/novice resources can understand the code easily
Differenet FrameWorks:
1)DataDriven Framework
2)keyword driven framework
3)Hybrid Framework
4)BDD
What is the difference in keyword driven vs data driven vs behavior driven frameworks?
Keyword-Driven Testing Framework:
- Focus: Keyword-driven testing, also known as table-driven testing, focuses on separating test automation logic from test data and test scripts.
- Components:
- Keywords: Actions or operations that represent test steps (e.g., "click," "type," "verify").
- Test Data: Input and expected output data.
- Test Scripts: A set of instructions that use keywords and test data to execute test cases.
- Advantages:
- Promotes reusability of keywords.
- Easy to maintain as test data and logic are separated.
- Non-technical team members can write and understand test cases.
- Example: A keyword-driven framework might have keywords like "login," "search," and "add to cart," which are combined with test data to create test scripts.
Data-Driven Testing Framework:
- Focus: Data-driven testing focuses on testing the same functionality with multiple sets of data to ensure the application behaves correctly across various inputs.
- Components:
- Test Data: Multiple sets of input and expected output data.
- Test Scripts: A single set of test scripts that can iterate over different sets of test data.
- Advantages:
- Efficient for testing multiple scenarios with minimal test script duplication.
- Easily extends test coverage by adding new data sets.
- Example: In a data-driven framework, you might have a single login test script that is executed with different username and password combinations from a data source (e.g., spreadsheet or database).
Behavior-Driven Testing Framework (BDD):
- Focus: Behavior-driven testing focuses on describing the expected behavior of an application in natural language terms, making it more accessible to non-technical stakeholders.
- Components:
- Feature Files: Text files written in a structured language (e.g., Gherkin) that describe features, scenarios, and steps.
- Step Definitions: Code that maps the steps in feature files to automation logic.
- Advantages:
- Encourages collaboration between technical and non-technical team members.
- Provides a clear understanding of the expected behavior of the application.
- Promotes test automation using a human-readable format.
- Example: In a BDD framework, you might have a feature file that describes a user registration feature with scenarios like "Register with valid credentials" and "Register with invalid credentials."
In summary, these testing frameworks differ in their approach and focus:
- Keyword-Driven Framework focuses on reusability and separating test logic from data.
- Data-Driven Framework focuses on testing the same functionality with different sets of data.
- Behavior-Driven Framework (BDD) focuses on describing expected behavior using natural language and encourages collaboration between technical and non-technical team members.
The choice of framework depends on your project's requirements, the team's expertise, and the level of collaboration needed between technical and non-technical stakeholders. Some projects may even combine elements from multiple frameworks to create a custom solution that best fits their needs.
HybridFramework:
It is combination of TestNG+Datadriven/KeywordDriven and Page Object Model Design Pattern.
TestNg is used to design the TestCases
Datadriven is used to test the same scenario with multiple sets of data
POM: how you we can design our page Elements/Objects
What is Page Object Model in Selenium?
Page Object Model, also known as POM, is a design pattern in Selenium that creates an object repository for storing all web elements. It is useful in reducing code duplication and improves test case maintenance.
In Page Object Model, consider each web page of an application as a class file. Each class file will contain only corresponding web page elements. Using these elements, testers can perform operations on the website under test
Advantages of Page Object Model- Helps with easy maintenance: POM is useful when there is a change in a UI element or there is a change in an action. An example would be: a drop-down menu is changed to a radio button. In this case, POM helps to identify the page or screen to be modified. As every screen will have different java files, this identification is necessary to make the required changes in the right files. This makes test cases easy to maintain and reduces errors.
- Helps with reusing code: As already discussed, all screens are independent. By using POM, one can use the test code for one screen, and reuse it in another test case. There is no need to rewrite code, thus saving time and effort.
- Readability and Reliability of scripts: When all screens have independent java files, one can easily identify actions that will be performed on a particular screen by navigating through the java file. If a change must be made to a certain section of code, it can be efficiently done without affecting other files.
Implementing POM in Selenium Project
1)Plain page object model
public static final By elementname=By.locator("locator");
Respective methods developed for above elements like doing actions on the elements, verifying whether that element is present in that page or not, page title is present or not. This is all developed using webdriver methods
to do action you have to write syntax :
public void clickElement(){
driver.findElement(elementname).click();
}
2)Using PageFactory class
What is Page Factory in Selenium?
Page Factory is a class provided by Selenium WebDriver to support Page Object Design patterns. In Page Factory, testers use @FindBy annotation. The initElements method is used to initialize web elements.
- @FindBy: An annotation used in Page Factory to locate and declare web elements using different locators. Below is an example of declaring an element using @FindBy
@FindBy(id="elementId") WebElement element;
Similarly, one can use @FindBy with different location strategies to find web elements and perform actions on them. Below are locators that can be used:
- ClassName
- CSS
- Name
- Xpath
- TagName
- LinkText
- PartialLinkText
- initElements(): initElements is a static method in Page Factory class. Using the initElements method, one can initialize all the web elements located by @FindBy annotation.
- lazy initialization: AjaxElementLocatorFactory is a lazy load concept in Page Factory. This is used to identify web elements only when they are used in any operation or activity. The timeout of a web element can be assigned to the object class with the help of the AjaxElementLocatorFactory.
//create a Constructor
public classname(){
PageFactory.initElements(driver,this);
}
@FindBy(locator="locatorvalue")
private WebElement elementName;
@FindBy(locator="locatorvalue")
private WebElement elementName;
@FindBy(locator="locatorvalue")
private WebElement elementName;
Respective methods developed for above elements like doing actions on the elements, verifying whether that element is present in that page or not, page title is present or not. This is all developed using webdriver methods
public void clickElement(){
elementName.click();
}
=====================================================================
PageFactory is an inbuilt POM concept in Selenium WebDriver, used for initialising Page objects or instantiating the Page object itself without using “FindElement" or "FindElements"
1) It uses annotations @FindBy to find WebElement, with attributes like tagName, partialLinkText, name, linkText, id, css, className, XPath.
2) "initElements()" is a method provided by the Page Factory class to initialize elements defined in a Page Object.
The initElements() method takes two parameters: a WebDriver instance and a Page Object instance. It scans the Page Object for any fields that are annotated with the @FindBy annotation and initializes them.
3) "@CacheLookUp" The end goal of this annotation is to make the code execute faster. It’s used mostly for WebElements in a test case. For the specific element, it keeps the WebElement in the cache memory after the first time it’s run.
Page Object Model:
Page Object Model (POM)
POM is a design pattern creating an Object Repository for web UI elements, aiming to reduce code duplication and improve test maintenance.
Each web page has a corresponding Page Class containing methods that perform operations on WebElements.
POM separates operations and flows in the UI from validation, making the code cleaner and more understandable.
It supports the reuse of page methods and gives methods realistic names for easy mapping with UI operations.
Why Not to use Page Factory?
(Refer this KeyNote from Selenium Team for its limitations: https://lnkd.in/gGsh3pgE)
1) The @CacheLookup annotation in PageFactory, intended for caching elements, can lead to StaleElementException If the DOM changes, it makes the element stale.
2) PageFactory is considered a “cumbersome and problematic implementation” with no significant benefits over direct runtime code element finding.
onFinish(ITestContext context) Invoked after all the tests have run and all their Configuration methods have been called. | |
void | onStart(ITestContext context) Invoked after the test class is instantiated and before any configuration method is called. |
void | onTestFailedButWithinSuccessPercentage(ITestResult result) Invoked each time a method fails but has been annotated with successPercentage and this failure still keeps it within the success percentage requested. |
void | onTestFailure(ITestResult result) Invoked each time a test fails. |
void | onTestSkipped(ITestResult result) Invoked each time a test is skipped. |
void | onTestStart(ITestResult result) Invoked each time before a test will be invoked. |
void | onTestSuccess(ITestResult result) Invoked each time a test succeeds. |
JetBrains Aqua – An IDE for Writing Tests You Can Be Proud Of.
Why do you need Aqua?
Designed for test automation
Aqua is the first JetBrains IDE created specifically for test automation. It's an all-in-one workspace that will help you boost your quality engineering productivity.
Web Inspector
The embedded Web Inspector allows you to view web applications in Aqua and capture any page elements required for automated tests. Working like a built-in browser, the Web Inspector lets you stay inside the IDE without switching to another tool.
Aqua’s embedded Web Inspector generates a unique CSS or XPath locator for a selected element on a web page and adds it to the source code. When Web Inspector is active, CSS and XPath code completion suggests and highlights locators for the most important web page elements.
Support for popular testing frameworks
Aqua supports the Selenium, Cypress, and Playwright testing frameworks, enabling you to create and run automated UI tests using your preferred tools. With JetBrains Aqua, you can write, run, and debug unit tests using JUnit, pytest, Jest, and other tools.
Comprehensive feature set
Aqua boasts a rich feature set with our HTTP Client for API testing, support for popular databases, and integration for Docker and version control. This feature set is available out of the box.
Support for multiple languages
Aqua is an IDE that understands Java, Python, JavaScript, TypeScript, Kotlin, and SQL. Just like any other JetBrains IDE, Aqua has powerful code completion and refactoring capabilities, helpful on-the-fly inspections, and a user-friendly debugger and test runner.
Modern UI
A modern and intuitive user interface makes it easy for both beginners and experienced professionals to get started with Aqua
==============================================================Select Maven – Maven Project as below :
Different Ways to run Framework Tests:
1)Run tests through testNG.xml
java.lang.NoClassDefFoundError: freemarker/template/TemplateModelException #295
java.lang.Error: Unresolved compilation problem: VERSION_2_3_29 cannot be resolved or is not a field #110
The isTraceEnabled()
method has been added to log4j 1.2.12, according to the Javadoc:
https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Logger.html#isTraceEnabled()
If you're using log4j (also if this is a transitive dependency on your project setup), please ensure that you take the latest version of log4j
Related link:https://github.com/jOOQ/jOOQ/issues/2085
2)Run tests through pom.xml
3)Run tests through command prompt
4)Run tests through batch file
5)Run tests through Jenkins CI tool
- Advantages of Jenkins include:
- It is an open source tool with great community support.
- It is easy to install.
- It has 1000+ plugins to ease your work. If a plugin does not exist, you can code it and share with the community.
- It is built with Java and hence, it is portable to all the major platforms.
- Anthill
- Bamboo
- Cruise Control
- Team City
STEP6)after setting username and password then login to jenkins
Click on Save and Apply buttons.
----------------------------------------------
12)give Root pom from github like below
Groovy's Domain-Specific Language (DSL) for Jenkins Pipelines
Introduction
In today's fast-paced development environment, automation is key to delivering software quickly and reliably. Jenkins, a leading open-source automation server, enables continuous integration and continuous delivery (CI/CD) for any project. At the heart of Jenkins is the Pipeline, which uses Groovy-based Domain-Specific Language (DSL) to automate build, test, and deployment processes. This article explores Groovy's DSL for Jenkins Pipelines, explaining its terminologies, structure, and usage through detailed examples.
Key Terminologies
Before diving into the DSL, it's crucial to understand the key terminologies:
1. Pipeline: A Pipeline defines a series of automated steps that take your code from version control to production.
2. Groovy: Groovy is an object-oriented programming language that enhances Java and is used to script Jenkins Pipelines.
3. DSL (Domain-Specific Language): A specialized language designed to solve problems in a specific domain—in this case, defining Jenkins Pipelines.
4. Stage: A stage is a block that groups steps in a Pipeline, typically representing a phase like "Build," "Test," or "Deploy."
5. Step: A step is a single task that Jenkins performs, such as running a shell command or executing a script.
6. Agent: An agent specifies where the Pipeline or a particular stage runs, whether on any available node, a specific node, or within a Docker container.
Step-by-Step Guide to Groovy DSL for Jenkins Pipelines
Step 1: Creating a Jenkins File
The Jenkinsfile is a text file containing the Pipeline definition, written using Groovy DSL. It should be placed in the root directory of your repository.
pipeline { agent any stages { stage('Build') { steps { echo 'Building...' } } stage('Test') { steps { echo 'Testing...' } } stage('Deploy') { steps { echo 'Deploying...' } } } }
Step 2: Defining Agents
Agents specify where the Pipeline or a specific stage runs. The agent any directive indicates that the Pipeline can run on any available agent.
pipeline {
agent {
label 'my-agent-label'
}
stages {
// Stages go here
}
}
Step 3: Creating Stages and Steps
Stages are used to organize the Pipeline into discrete phases. Each stage can contain multiple steps that perform specific tasks.
stage('Build') {
steps {
sh 'make' // Execute shell command to build the project
}
}
stage('Test') {
steps {
sh 'make test' // Execute shell command to test the project
}
}
stage('Deploy') {
steps {
sh 'make deploy' // Execute shell command to deploy the project
}
}
Step 4: Using Post-Actions
Post actions are blocks that define steps to run at the end of a Pipeline or stage, regardless of the outcome.
post { always { echo 'This will always run' } success { echo 'This will run only if the Pipeline succeeds' } failure { echo 'This will run only if the Pipeline fails' } }
Step 5: Parallel Execution
Jenkins Pipelines can run multiple stages in parallel to optimize the CI/CD process. This is done using the parallel directive.
stage('Parallel Execution') {
parallel {
stage('Unit Tests') {
steps {
sh 'make test-unit'
}
}
stage('Integration Tests') {
steps {
sh 'make test-integration'
}
}
}
}
Practical Examples
Example 1: Simple Pipeline
This example demonstrates a basic Pipeline with build, test, and deploy stages.
pipeline {
agent any
stages {
stage('Compile') {
steps {
echo 'Compiling..'
sh 'javac MyClass.java'
}
}
stage('Unit Test') {
steps {
echo 'Running Unit Tests..'
sh 'java MyClassTest'
}
}
stage('Deploy') {
steps {
echo 'Deploying Application..'
sh 'scp MyClass.class user@host:/deploy'
}
}
}
}
Example 2: Declarative Pipeline with Notifications
This example shows how to add email notifications for success and failure outcomes.
pipeline { agent any stages { stage('Build') { steps { echo 'Building...' sh 'make build' } } stage('Test') { steps { echo 'Testing...' sh 'make test' } } } post { success { mail to: 'team@example.com', subject: "Build Successful: ${env.JOB_NAME} ${env.BUILD_NUMBER}", body: "Good job! The build was successful." } failure { mail to: 'team@example.com', subject: "Build Failed: ${env.JOB_NAME} ${env.BUILD_NUMBER}", body: "Unfortunately, the build failed. Please check the Jenkins logs for more details." } } }
FAQs
Q1: What is the primary benefit of using Groovy DSL for Jenkins pipelines?
A1: The primary benefit is the ability to define complex, multi-step workflows in a clear, readable, and maintainable manner. Groovy DSL's flexibility allows for the customization of build, test, and deployment processes to fit specific project requirements.
Q2: Can I use Jenkins Pipelines without knowing Groovy?
A2: While a basic understanding of Groovy helps in writing and maintaining Jenkins Pipelines, the DSL is designed to be user-friendly. Jenkins' documentation and community support can assist in learning the necessary Groovy basics.
Q3: How do I debug issues in my Jenkins Pipeline?
A3: You can use the echo command to print debug information to the Jenkins console. Additionally, Jenkins provides detailed logs for each step of the Pipeline, which can help identify and resolve issues.
Q4: What is the difference between Declarative and Scripted Pipelines in Jenkins?
A4: Declarative Pipelines provide a more structured and user-friendly syntax, ideal for simpler, standardized tasks. Scripted Pipelines offer greater flexibility and are suited for more complex, customized workflows. Both use Groovy DSL but differ in their structure and capabilities.
Q5: How do I handle parallel execution in Jenkins Pipelines?
A5: You can define parallel stages in a Jenkins Pipeline using the parallel directive. This allows multiple stages to run simultaneously, speeding up the overall pipeline execution.
stage('Parallel Execution') {
parallel {
stage('Unit Tests') {
steps {
sh 'make test-unit'
}
}
stage('Integration Tests') {
steps {
sh 'make test-integration'
}
}
}
}
Conclusion
Groovy's DSL for Jenkins Pipelines offers a powerful and flexible way to define CI/CD workflows. By understanding the core concepts and leveraging the provided examples, you can create robust Pipelines tailored to your project's needs. Whether you're a novice or an experienced DevOps engineer, mastering Jenkins Pipelines will significantly enhance your automation capabilities.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.