Hi Raghav, you are like amazing. i knew BDD framework i was working and running the BDD scripts for production environment, Still after watching your videos feeling like ... yess.... now i have connected all the dots. Thank you from the bottom of my heart.
Thank you so much for your sessions.its really helpful to us and the persons who starting from scratch they can acquire knowledge. I am so thankful to you ant cant be silent to appreciate you Waiting for upcoming sessions.
Hii Raghav sir, really happy again am here to learn cucumber framework,few months ago I have learnt api testing using postman through your videos. Am always thankful 🙏.
Since we have covered Given,When,Then in the Background part, we can skip the 'Given' statement in the actual scenario? So Given statement is not mandatory in every scenario?
Mandar Yes, you can skip the 'Given' statement in the actual scenario if you have covered it in the Background part. The 'Given', 'When', and 'Then' statements are not mandatory in every scenario, but they are generally considered to be best practice. The Background part is used to set up the state of the application before each scenario is executed. This can be useful for setting up common data or for ensuring that the application is in a known state before each scenario. Here is an example of a feature file that uses the Background part to set up a 'Given' statement: ``` Feature: Login Background: Given I am on the login page Scenario: Login with valid credentials When I enter the username "johndoe" And I enter the password "password" And I click the login button Then I should be logged in Scenario: Login with invalid credentials When I enter the username "invalid" And I enter the password "invalid" And I click the login button Then I should see an error message ``` In the above example, the 'Given I am on the login page' statement is set up in the Background part. This means that it will be executed before each scenario is executed. This allows us to skip the 'Given' statement in the actual scenarios. Whether or not to use the Background part is a matter of personal preference. However, using the Background part can help to make your feature files more readable and maintainable
@raghav, thank you for this video, its really helpful for my framework and i just want how to keep logout scenario as background, as i understood background working as pre-requisite and after steps execution, can i use this concept?, If yes, how can i do that, kindly help me out
Hi Raghav. Can you please help me with one query? I understand the background runs before each scenario of the feature file.How can we add common steps of 'logout' in the feature? I guess we cannot do it with Background as i m expecting the logout steps to be executed after each scenario. If my guess is correct,then what is the option to add common logout steps in feature files,provided i m not using hooks in gluecode?
Hi Saheli If you want to include common logout steps in each scenario of a feature file without using hooks in glue code, you can consider using the Scenario Outline feature of Cucumber. Here is an example: Feature: Logout functionality Scenario Outline: User logs out of the application Given user is logged in When user clicks on the logout button Then user is logged out successfully Examples: | username | password | | user1 | pass1 | | user2 | pass2 | | user3 | pass3 | In this example, the Scenario Outline is used to define a set of scenarios with common steps. Each row in the Examples table represents a set of data for the Given step that logs in the user. The When and Then steps are common for all scenarios. You can add more steps after the Then step for performing additional actions, such as navigating to the home page or closing the browser.
Hi Raghav, If I have 10 steps in two scenarios. In that steps (1 to 6) and steps (9 to10) are common for both the scenarios. Only steps (7 and 8) are different for both the scenarios. In this case I can use background for steps 1 to 6 but steps (9 to 10) is there a way in background. I know we can handle it through “after” but is there a way can I handle through steps in features. Please let me know. Thanks
Hi Vijay, so you can have the backend function same for the common steps and in the feature file you can write the complete scenario, It will increase the readability and at the backend (step definition) there will be no duplicate functions
After launching the application, how to search a field like Customer ID with mutiple data using Examples in Cucumber. My issue is when I am passing multiple data in Examples, it executes correctly with first data Customer ID value but with second data Customer ID value, its going to Background section of Feature file i.e.,Login page. Ideally the Application should search with second Customer ID value without going to Background section. How to achieve it.
Hi Reshma, I don't think you can do it with Background, still check this discussion - stackoverflow.com/questions/28767229/how-do-you-add-an-examples-table-to-a-background-in-a-cucumber-feature-file
Hy Raghav Sir, I am a Big fan of you and i follow your all the videos related to selenium and java. I am facing a problem i.e. If i have 5feature file and in every feature file one thing is common i.e User Already login to application then how can i do that for every feature file? Please suggest.
Hi Raghav. I get this error when because of the "html:target/HTMLReports" plugin: "java.lang.IllegalArgumentException: Couldn't create a file output stream for 'target\HTMLReports'. Make sure the the file isn't a directory."
Hi, @Automation Step by Step, On using the background feature, the basic steps are executing fine but when the actual step of the scenario comes, the browser opens twice. So pls suggest how to overcome it.
Karthik There are a few possible reasons why the browser is opening twice when you use the `background` feature in Selenium with Cucumber Java. One possibility is that you are initializing the browser twice. This can happen if you are initializing the browser in the background steps and then again in the scenario steps. Another possibility is that you are not closing the browser properly. This can happen if you are not closing the browser in the `afterEach()` hook. To overcome this problem, you can try the following: * Make sure that you are only initializing the browser once. You can do this by initializing the browser in the `beforeEach()` hook and then closing it in the `afterEach()` hook. * Make sure that you are closing the browser properly. You can do this by adding a call to the `driver.quit()` method in the `afterEach()` hook. Here is an example of how to initialize and close the browser in the `beforeEach()` and `afterEach()` hooks: ```java @Before public void before() { driver = new ChromeDriver(); } @After public void after() { driver.quit(); } ``` You can also try using a page object model to manage the browser. A page object model is a design pattern that helps to organize test code and make it more reusable. When you use a page object model, you can create a separate page object for each page in your application. Each page object will have methods for interacting with the elements on the page. To use a page object model, you would first create a page object for the page that you are testing. Then, you would use the page object to interact with the elements on the page. For example, the following code would create a page object for the login page and then use the page object to login to the application: ```java public class LoginPage { private WebDriver driver; public LoginPage(WebDriver driver) { this.driver = driver; } public void login(String username, String password) { driver.findElement(By.id("username")).sendKeys(username); driver.findElement(By.id("password")).sendKeys(password); driver.findElement(By.id("login")).click(); } } @Given("I am on the login page") public void i_am_on_the_login_page() { LoginPage loginPage = new LoginPage(driver); loginPage.get(); } @When("I enter my username and password") public void i_enter_my_username_and_password() { LoginPage loginPage = new LoginPage(driver); loginPage.login("username", "password"); } @Then("I should be logged in") public void i_should_be_logged_in() { // ... } ``` Using a page object model can help to prevent the browser from opening twice, because you will only need to initialize the browser once in the `beforeEach()` hook. If you are still having problems, you can post a question on the Selenium forum or Stack Overflow. There are a number of experienced Selenium users who can help you troubleshoot the problem. I hope this helps
Hi raghav, if I want to add tags to the feature file, how does it work with background. When i added tag to the scenario, it failed as background was not running
Sarayu When using tags in a Selenium Java Cucumber automation testing framework, it's important to understand how tags interact with background steps. Tags are used to categorize and group scenarios, while background steps define common preconditions that are executed before each scenario in a feature. **Tag Inheritance** Tags are inherited by child elements. This means that if you place a tag above a feature, it will be inherited by all scenarios within that feature. However, background steps are not considered child elements of the feature, so they won't inherit the tag directly. **Scenario Tag vs. Background Tag** When you add a tag to a scenario, the tag is applied to that specific scenario and doesn't affect the background steps. This means that if you have a background step that is used by multiple scenarios, it will be executed before each scenario, regardless of whether the scenarios have the same tag or not. **Background Tag Execution** To ensure that the background step is executed only when the scenarios with the same tag are executed, you can add the tag to the background step itself. This will make the background step skip execution for scenarios that don't have the matching tag. Here's an example of how to add a tag to the background step: ```gherkin @tag1 Feature: My Feature Scenario: Scenario with tag1 Given I am on the login page Scenario: Scenario without tag1 Given I am on the home page ``` In this example, the background step will only be executed before the `Scenario with tag1` since it has the same tag. The `Scenario without tag1` will still execute, but the background step will be skipped. By understanding how tags interact with background steps, you can effectively structure your feature files and ensure that common preconditions are executed only when relevant scenarios are run.
Hi , raghav sir, one problem I encountered is "Can we run hooks before running the background?" cause i am using hooks to do the browser setup and it doesnot run in case of background.
Yes, you can run hooks before running the background in Selenium Cucumber Java. In fact, this is the recommended way to do it. The background is a section of code that runs before each scenario in a feature file. The hooks are blocks of code that run before or after each scenario or step. The recommended way to run the hooks before the background is to define the hooks in a separate class. This class can then be imported into the step definition class and the background section. Here is an example of how you can do this: ``` public class Hooks { @Before public void setUp() { // Setup the browser } @After public void tearDown() { // Tear down the browser } } ``` ``` public class StepDefinitions { @Before public void before() { // Run the hooks Hooks.setUp(); } @Background public void background() { // Do something in the background } @After public void after() { // Tear down the hooks Hooks.tearDown(); } } ``` In this example, the `Hooks` class defines two hooks, `@Before` and `@After`. The `StepDefinitions` class imports the `Hooks` class and uses the `@Before` hook to run the `setUp()` method before each scenario. The `background()` method is defined in the `StepDefinitions` class and runs in the background before each scenario. I hope this helps
Hi Raghav, I have used browser setup and teardown in two different step definition file because of that when I am running 2 different feature file it invoked browser twice while execution. How can I handle this issue
Suwarna When using Selenium with Cucumber, it's common to encounter issues with browser setup and teardown, especially when they are defined in separate step definition files. This can lead to multiple browser instances being invoked unintentionally. To handle this issue, you can implement a shared WebDriver instance across different step definitions. Here's how you can approach it: 1. Use a Singleton Pattern for WebDriver: Create a WebDriver instance that follows the singleton pattern. This ensures that only one instance of the WebDriver is created and shared across all step definitions. 2. Implement a Base Class: Create a base class that initializes the WebDriver and use this base class in all your step definition files. This way, the initialization code is written only once, and the same WebDriver instance is used throughout the test execution. 3. Utilize Dependency Injection: Tools like PicoContainer can help you manage your WebDriver instance and other shared objects across different step definitions. By using dependency injection, you can ensure that the same instance of WebDriver is passed to all the step definitions that require it. 4. Configure Hooks Properly: Use Cucumber hooks (`@Before` and `@After`) to set up and tear down the WebDriver. Make sure that these hooks are configured to run only once per test run, not once per feature file. 5. Centralize Browser Management: Centralize your browser management logic in one place. This could be a utility class or a configuration class that handles the creation and destruction of the WebDriver instance. Here's a basic example of how you might implement a shared WebDriver using a base class: ```java public class DriverBase { private static WebDriver driver; public static WebDriver getDriver() { if (driver == null) { // Initialize the WebDriver instance here (e.g., new ChromeDriver()) driver = new ChromeDriver(); } return driver; } @AfterAll public static void tearDown() { if (driver != null) { driver.quit(); driver = null; } } } ``` In your step definition files, you would then use `DriverBase.getDriver()` to obtain the WebDriver instance. By following these steps, you should be able to manage a single WebDriver instance across multiple feature files and step definition files, preventing multiple browsers from being invoked during your test execution. Remember to also review your Cucumber configuration to ensure it aligns with these changes Let me know how it goes..
Hi Raghav, Thank you for valuable knowledge, I have one one question after applying some steps in my background keyword in my console not showing answer like your answer I my console showing background (steps from background) the my scenario again background and scenario Example.. Background: Given a registered user exists Given user is on Amazon login page When user enters user name And user enters password And user click on login button Then user navigate to order page Scenario: Check open order details When User click on open order link Then user check open order details Background: Given a registered user exists Given user is on Amazon login page When user enters user name And user enters password And user click on login button Then user navigate to order page Scenario: Check Cancelled order details When User click on Cancelled order link Then user check Cancelled order details What should i do for this i want answer like your answer?? Plz help me.
@@RaghavPal Hi Raghav I saw your first video again slowly then I found my mistake now I have corrected that issue and code is running properly, Thank you for your help and reply in early morning
Hi Raghav, When I run the feature file, I am getting the warning "You are using deprecated Main class. Please use io.cucumber.core.cli.Main" along with an exception "java.util.concurrent.ExecutionException". The code snippets aren't displayed in the console once I've run the feature file. It only displays "0 Scenarios 0 Steps 0m0.302s" Can you please help me on this?
Hi Ankush, pls refresh the reports folder and check again, pls check if you have done all the setup and all required dependencies are added, Can check changing the ver
Hi Tulasi, in cucumber Pretty Format generates the Cucumber test report in the HTML format, i.e. an HTML file. It is the most readable report format. It generates the report in the same way as it is a feature file, so tracing is also made easy.
@@RaghavPal But I see there is an XML for pretty report. What about this XML report. I am thinking that pretty generates XML report. Correct me if I am wrong
Hi Mojtaba, Background is used to set up a precondition Background runs before each scenario, but after any Before hooks. This will help www.numpyninja.com/post/hooks-vs-background-cucumber#:~:text=After%20hooks%20will%20be%20run,undefined%2C%20pending%20or%20skipped%20steps.&text=Background%20is%20used%20to%20set,but%20after%20any%20Before%20hooks.
Hello Raghav how can we pass test data in background tag i have one scenario which repeated so decided to used background but with statement i have to pass test data can you give any reference i tried it but it not work. please any who can help me in this.
Pawan When using Cucumber with Selenium Java, the `Background` section in your feature file allows you to define common steps that run before each scenario within that feature. However, passing test data directly into the `Background` section is not directly supported. The `Background` steps are meant to set up the initial state of the system under test and should not change for each scenario That said, there are a few approaches you can take to achieve your goal: 1. Predefined Data in Background Steps: - Define your test data (e.g., usernames, passwords, search queries) as constants or variables in your step definitions. - In the `Background` section, use these predefined values for common steps (e.g., logging in). - Example: ```gherkin Feature: Test Background Background: Given User is Logged In And User has a valid product in the cart Scenario: Search a product and add it to the cart When User searches for a product And adds the product to the cart Then the cart should display the added item ``` 2. Scenario Outline with Examples: - If your repeated scenario involves variations of the same steps with different data, consider using a `Scenario Outline` with an `Examples` table. - Example: ```gherkin Feature: Test Background Background: Given User is Logged In Scenario Outline: Search a product and add it to the cart When User searches for "" And adds the product to the cart Then the cart should display the added item Examples: | product | | Lenovo Laptop | | iPhone | ``` 3. Data Tables in Steps: - If you need dynamic data for each scenario, use data tables within your steps. - Example: ```gherkin Feature: Test Background Background: Given User is Logged In Scenario: Search a product and add it to the cart When User searches for a product And adds the product "" to the cart Then the cart should display the added item Examples: | product | | Lenovo Laptop | | iPhone | ``` - In your step definitions, extract the data from the data table: ```java @When("^User searches for a product$") public void user_searches_for_product(DataTable dataTable) { List data = dataTable.asMaps(String.class, String.class); String product = data.get(0).get("product"); // Perform search based on the product } ``` Remember that the `Background` section is primarily for setting up the context, and dynamic test data should be handled within the individual scenarios. Choose the approach that best fits your requirements and keeps your feature files clean and maintainable --
Trilekhya Here's how to parameterize username and password for background steps in Selenium Cucumber: 1. Define Parameters in Feature File: - Use angle brackets `` to specify parameters in your Background steps: ```gherkin Background: Given I am on the login page When I enter username as "" and password as "" And I click on the login button ``` 2. Pass Values from Step Definitions: - Use the `Scenario` object to retrieve parameter values from the feature file: ```java @Given("^I am on the login page$") public void i_am_on_the_login_page() { driver.get("your-login-page.com"); } @When("^I enter username as \"([^\"]*)\" and password as \"([^\"]*)\"$") public void i_enter_username_and_password(String username, String password) { WebElement usernameField = driver.findElement(By.id("username")); usernameField.sendKeys(username); WebElement passwordField = driver.findElement(By.id("password")); passwordField.sendKeys(password); driver.findElement(By.id("login_button")).click(); } ``` 3. Manage Parameter Values: - Data Tables: Store values in a data table within the feature file: ```gherkin Examples: | username | password | | user1@example.com | password123 | | user2@example.com | password456 | ``` - External Files: Load values from external sources like CSV files or config files. - Hook Implementations: Use Hooks (e.g., `@Before`) to fetch values from databases or APIs. 4. Access Parameters in Background Steps: - Parameters defined in the Feature file are available to Background steps as well as individual scenarios. Additional Considerations: - Parameter Type Flexibility: Cucumber supports various parameter types (e.g., numbers, lists, custom objects). - Organization and Reusability: Consider organizing parameters in separate files or shared resources for better maintainability. - Security: Handle sensitive information like passwords with care, using encryption or environment variables.
@@RaghavPal , I am getting the error at Examples, saying "Found examples when expecting one of: [comment, doc_string, row, scenario, scenario_outline, step, tag]. (Current state: step).". How to fix this?
Trilekhya Common Causes and Solutions: 1. Incorrect Placement of Examples: - Ensure the `Examples:` keyword is placed directly after the `Scenario Outline:` keyword, with a blank line separating them. - Example: ```gherkin Scenario Outline: Login with different credentials Given I am on the login page When I enter and And I click the login button Then I should be redirected to the dashboard Examples: | username | password | | user1 | password1 | | user2 | password2 | ``` 2. Missing Blank Line: - Verify that there's a blank line between the `Scenario Outline:` and `Examples:` keywords. 3. Incorrect Indentation: - Maintain proper indentation: - `Scenario Outline:` and `Examples:` should be flush left. - Steps and table rows should be indented one level. 4. Missing Step Definitions: - Ensure you have matching step definitions in your Java code for all steps in your feature file. 5. Cucumber Version Incompatibility: - Check for compatibility issues between your Cucumber version and Gherkin syntax. - Consider updating Cucumber if necessary. Additional Troubleshooting Tips: - Review Feature File Syntax: Carefully examine your feature file for any structural errors or typos. - Check Glue Code: Ensure your step definitions are correctly implemented in your Java code. - Consult Documentation: Refer to Cucumber's documentation for specific guidelines and examples. - Utilize IDE Help: If using an IDE, leverage its syntax highlighting and validation features to identify errors. - Run in Debug Mode: Debugging can reveal details about the error's origin.
Hi Aniketh, ccording to the Cucumber documentation, here is what Before does: Before hooks will be run before the first step of each scenario. They will run in the same order of which they are registered. And here is what Background does: Background allows you to add some context to the scenarios in a single feature. A Background is much like a scenario containing a number of steps. The difference is when it is run. The background is run before each of your scenarios but after any of your Before Hooks. In facts, as you noticed already, their structures are a little bit different. The common practice is to use them as follows: Use Background when you provide customer-readable pre-conditions to your scenarios Use Before when you have to do some technical setup before your scenarios But the main thing to understand here is the order of the operations: Before Hook 1 -> Before Hook 2 -> ... -> Background -> Scenario They just represent different levels of pre-conditions. stackoverflow.com/questions/37585052/cucumber-whats-the-difference-between-background-and-before-tag
Hi Raghav, you are like amazing. i knew BDD framework i was working and running the BDD scripts for production environment, Still after watching your videos feeling like ... yess.... now i have connected all the dots.
Thank you from the bottom of my heart.
Glad I could help Suruchi
Can’t thank you enough Raghav, you are an amazing soul, the way you deliver and teach us is exceptional!! Thanks a lot brother!
Most welcome Dhruv
Raghav - Virat Kohli of QA world.. as usual the most easiest explanation that a beginner can also understand.. Best Wishes.. Keep it coming
Thanks for the kind words
No MS DHONI OF QA WORLD RAGHAV
Thank you so much for your sessions.its really helpful to us and the persons who starting from scratch they can acquire knowledge.
I am so thankful to you ant cant be silent to appreciate you
Waiting for upcoming sessions.
Glad to hear that Akhil
Very good. I just wish I could click on your step definition file to have a good look at it. Each tutorial in this series gets faster and faster! :)
Hi Laura, You can get the project from github github.com/Raghav-Pal/SeleniumCucumberBDD
Thanks a lot for your all series. I appreciate your all efforts and thank you for sharing your knowledge. Well done!
So nice of you
Thank you so much Raghav for making the content so easy and precise to learn.
Most welcome Monica
Raghav Sir Very Awesome Videos.....Great Explanation, Great Content, Clear Voice, Perfect Combination of all the things....♥
Thanks a lot
Love your "Useful Tips" section in the video
Thanks
very useful session...gone through full series.. teaching skill is also too good
Glad to hear that Sonali
Thanks.... Impressive Content in simple language
Most welcome!
Hii Raghav sir, really happy again am here to learn cucumber framework,few months ago I have learnt api testing using postman through your videos.
Am always thankful 🙏.
Hii sir can u provide cucumber playlist if possible.
Thanks in advance
Hi Tulasi, can check all here automationstepbystep.com/
Really very informative session, thanks for all your help 😊
Always welcome Kumaran
Thank you so much sir.... For valuable information
Most welcome
Great explanation.
Thanks Dushan
Your videos are awesome.
Glad you like them Sumeet
Thanhk you for the explanation
Most welcome Tarik
Thanks a lot man!! i came across your channel by mistake but it is worth a mistake.
Glad I could help Mayank, can check all automationstepbystep.com/
Thank you sir.
Most welcome Suchi
Nice video ....please upload videos on how to add extent reports in cucumber
Sure Viswhwajeet
nice video plz upload more topic
Sure I will Amit
Amazing!
Thanks for watching
Since we have covered Given,When,Then in the Background part, we can skip the 'Given' statement in the actual scenario? So Given statement is not mandatory in every scenario?
Mandar
Yes, you can skip the 'Given' statement in the actual scenario if you have covered it in the Background part. The 'Given', 'When', and 'Then' statements are not mandatory in every scenario, but they are generally considered to be best practice.
The Background part is used to set up the state of the application before each scenario is executed. This can be useful for setting up common data or for ensuring that the application is in a known state before each scenario.
Here is an example of a feature file that uses the Background part to set up a 'Given' statement:
```
Feature: Login
Background:
Given I am on the login page
Scenario: Login with valid credentials
When I enter the username "johndoe"
And I enter the password "password"
And I click the login button
Then I should be logged in
Scenario: Login with invalid credentials
When I enter the username "invalid"
And I enter the password "invalid"
And I click the login button
Then I should see an error message
```
In the above example, the 'Given I am on the login page' statement is set up in the Background part. This means that it will be executed before each scenario is executed. This allows us to skip the 'Given' statement in the actual scenarios.
Whether or not to use the Background part is a matter of personal preference. However, using the Background part can help to make your feature files more readable and maintainable
@raghav, thank you for this video, its really helpful for my framework and i just want how to keep logout scenario as background, as i understood background working as pre-requisite and after steps execution, can i use this concept?, If yes, how can i do that, kindly help me out
Hi, yes, you can use this if it fits your scenario and requirements
Nice video plz make video on cucumber with excel read and write using datatables
Sure, will do
Hi Raghav. Can you please help me with one query? I understand the background runs before each scenario of the feature file.How can we add common steps of 'logout' in the feature? I guess we cannot do it with Background as i m expecting the logout steps to be executed after each scenario. If my guess is correct,then what is the option to add common logout steps in feature files,provided i m not using hooks in gluecode?
Hi Saheli
If you want to include common logout steps in each scenario of a feature file without using hooks in glue code, you can consider using the Scenario Outline feature of Cucumber.
Here is an example:
Feature: Logout functionality
Scenario Outline: User logs out of the application
Given user is logged in
When user clicks on the logout button
Then user is logged out successfully
Examples:
| username | password |
| user1 | pass1 |
| user2 | pass2 |
| user3 | pass3 |
In this example, the Scenario Outline is used to define a set of scenarios with common steps. Each row in the Examples table represents a set of data for the Given step that logs in the user. The When and Then steps are common for all scenarios.
You can add more steps after the Then step for performing additional actions, such as navigating to the home page or closing the browser.
Thanks for the video.Can you pls cover the cucumber testing integration
Yes I will Jayanta, Let me know the exact topics
Raghav-Currently we are using Junit to run Test Runner. Instead of Junit how to use Testng for running the TestRunner
Okay will plan on this
Hello Raghav, Please let me know if you will be able to provide sessions for money, it can be 1:1 individual or a group. Please let me know on it.
No Chaitu
Nice video raghav thanks..Is there a way in cucumber can we put common steps at the bottom steps like logout?
Hi Vijay, why exactly you want to do that, Can check hooks video
Hi Raghav, If I have 10 steps in two scenarios. In that steps (1 to 6) and steps (9 to10) are common for both the scenarios. Only steps (7 and 8) are different for both the scenarios. In this case I can use background for steps 1 to 6 but steps (9 to 10) is there a way in background. I know we can handle it through “after” but is there a way can I handle through steps in features. Please let me know. Thanks
Hi Vijay, so you can have the backend function same for the common steps and in the feature file you can write the complete scenario, It will increase the readability and at the backend (step definition) there will be no duplicate functions
@@RaghavPal but in feature file still I have to repeat the steps for each scenario right
After launching the application, how to search a field like Customer ID with mutiple data using Examples in Cucumber. My issue is when I am passing multiple data in Examples, it executes correctly with first data Customer ID value but with second data Customer ID value, its going to Background section of Feature file i.e.,Login page. Ideally the Application should search with second Customer ID value without going to Background section. How to achieve it.
Hi Pranav, will need to check the setup and how you are doing referencing, Pls check some online examples
Hi Raghav,
Is it possible to give parameters in Background as we do in Scenario Outline?
Hi Reshma, I don't think you can do it with Background, still check this discussion - stackoverflow.com/questions/28767229/how-do-you-add-an-examples-table-to-a-background-in-a-cucumber-feature-file
Hy Raghav Sir,
I am a Big fan of you and i follow your all the videos related to selenium and java.
I am facing a problem i.e.
If i have 5feature file and in every feature file one thing is common i.e User Already login to application then how can i do that for every feature file? Please suggest.
Hi Biswamber, you can use before tag
stackoverflow.com/questions/37585052/cucumber-whats-the-difference-between-background-and-before-tag
@@RaghavPal Thnk you so much sir🙏 when no body replied that time you replied. I am really appreciate. After 1year of the video also you replied me.
@@RaghavPal I am done what i wanted.
All the best
Hi Raghav. I get this error when because of the "html:target/HTMLReports" plugin: "java.lang.IllegalArgumentException: Couldn't create a file output stream for 'target\HTMLReports'.
Make sure the the file isn't a directory."
Hi Karabo, first create a folder manually and then give its location in the code
Hi, @Automation Step by Step,
On using the background feature, the basic steps are executing fine but when the actual step of the scenario comes, the browser opens twice. So pls suggest how to overcome it.
Karthik
There are a few possible reasons why the browser is opening twice when you use the `background` feature in Selenium with Cucumber Java.
One possibility is that you are initializing the browser twice. This can happen if you are initializing the browser in the background steps and then again in the scenario steps.
Another possibility is that you are not closing the browser properly. This can happen if you are not closing the browser in the `afterEach()` hook.
To overcome this problem, you can try the following:
* Make sure that you are only initializing the browser once. You can do this by initializing the browser in the `beforeEach()` hook and then closing it in the `afterEach()` hook.
* Make sure that you are closing the browser properly. You can do this by adding a call to the `driver.quit()` method in the `afterEach()` hook.
Here is an example of how to initialize and close the browser in the `beforeEach()` and `afterEach()` hooks:
```java
@Before
public void before() {
driver = new ChromeDriver();
}
@After
public void after() {
driver.quit();
}
```
You can also try using a page object model to manage the browser. A page object model is a design pattern that helps to organize test code and make it more reusable. When you use a page object model, you can create a separate page object for each page in your application. Each page object will have methods for interacting with the elements on the page.
To use a page object model, you would first create a page object for the page that you are testing. Then, you would use the page object to interact with the elements on the page. For example, the following code would create a page object for the login page and then use the page object to login to the application:
```java
public class LoginPage {
private WebDriver driver;
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void login(String username, String password) {
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.id("login")).click();
}
}
@Given("I am on the login page")
public void i_am_on_the_login_page() {
LoginPage loginPage = new LoginPage(driver);
loginPage.get();
}
@When("I enter my username and password")
public void i_enter_my_username_and_password() {
LoginPage loginPage = new LoginPage(driver);
loginPage.login("username", "password");
}
@Then("I should be logged in")
public void i_should_be_logged_in() {
// ...
}
```
Using a page object model can help to prevent the browser from opening twice, because you will only need to initialize the browser once in the `beforeEach()` hook.
If you are still having problems, you can post a question on the Selenium forum or Stack Overflow. There are a number of experienced Selenium users who can help you troubleshoot the problem.
I hope this helps
@@RaghavPal Thanks a lot raghav. This helped me. Thanks for the support.
Hi raghav, if I want to add tags to the feature file, how does it work with background. When i added tag to the scenario, it failed as background was not running
Sarayu
When using tags in a Selenium Java Cucumber automation testing framework, it's important to understand how tags interact with background steps. Tags are used to categorize and group scenarios, while background steps define common preconditions that are executed before each scenario in a feature.
**Tag Inheritance**
Tags are inherited by child elements. This means that if you place a tag above a feature, it will be inherited by all scenarios within that feature. However, background steps are not considered child elements of the feature, so they won't inherit the tag directly.
**Scenario Tag vs. Background Tag**
When you add a tag to a scenario, the tag is applied to that specific scenario and doesn't affect the background steps. This means that if you have a background step that is used by multiple scenarios, it will be executed before each scenario, regardless of whether the scenarios have the same tag or not.
**Background Tag Execution**
To ensure that the background step is executed only when the scenarios with the same tag are executed, you can add the tag to the background step itself. This will make the background step skip execution for scenarios that don't have the matching tag.
Here's an example of how to add a tag to the background step:
```gherkin
@tag1
Feature: My Feature
Scenario: Scenario with tag1
Given I am on the login page
Scenario: Scenario without tag1
Given I am on the home page
```
In this example, the background step will only be executed before the `Scenario with tag1` since it has the same tag. The `Scenario without tag1` will still execute, but the background step will be skipped.
By understanding how tags interact with background steps, you can effectively structure your feature files and ensure that common preconditions are executed only when relevant scenarios are run.
Hello Raghav , can we add Login Step to Background with different Login Data ??
Hi, I am not completely sure if we can use parameterized backgrounds. will need to check on this
Hi , raghav sir, one problem I encountered is "Can we run hooks before running the background?" cause i am using hooks to do the browser setup and it doesnot run in case of background.
Yes, you can run hooks before running the background in Selenium Cucumber Java. In fact, this is the recommended way to do it.
The background is a section of code that runs before each scenario in a feature file. The hooks are blocks of code that run before or after each scenario or step.
The recommended way to run the hooks before the background is to define the hooks in a separate class. This class can then be imported into the step definition class and the background section.
Here is an example of how you can do this:
```
public class Hooks {
@Before
public void setUp() {
// Setup the browser
}
@After
public void tearDown() {
// Tear down the browser
}
}
```
```
public class StepDefinitions {
@Before
public void before() {
// Run the hooks
Hooks.setUp();
}
@Background
public void background() {
// Do something in the background
}
@After
public void after() {
// Tear down the hooks
Hooks.tearDown();
}
}
```
In this example, the `Hooks` class defines two hooks, `@Before` and `@After`. The `StepDefinitions` class imports the `Hooks` class and uses the `@Before` hook to run the `setUp()` method before each scenario. The `background()` method is defined in the `StepDefinitions` class and runs in the background before each scenario.
I hope this helps
Hi Raghav, I have used browser setup and teardown in two different step definition file because of that when I am running 2 different feature file it invoked browser twice while execution. How can I handle this issue
Suwarna
When using Selenium with Cucumber, it's common to encounter issues with browser setup and teardown, especially when they are defined in separate step definition files. This can lead to multiple browser instances being invoked unintentionally. To handle this issue, you can implement a shared WebDriver instance across different step definitions. Here's how you can approach it:
1. Use a Singleton Pattern for WebDriver: Create a WebDriver instance that follows the singleton pattern. This ensures that only one instance of the WebDriver is created and shared across all step definitions.
2. Implement a Base Class: Create a base class that initializes the WebDriver and use this base class in all your step definition files. This way, the initialization code is written only once, and the same WebDriver instance is used throughout the test execution.
3. Utilize Dependency Injection: Tools like PicoContainer can help you manage your WebDriver instance and other shared objects across different step definitions. By using dependency injection, you can ensure that the same instance of WebDriver is passed to all the step definitions that require it.
4. Configure Hooks Properly: Use Cucumber hooks (`@Before` and `@After`) to set up and tear down the WebDriver. Make sure that these hooks are configured to run only once per test run, not once per feature file.
5. Centralize Browser Management: Centralize your browser management logic in one place. This could be a utility class or a configuration class that handles the creation and destruction of the WebDriver instance.
Here's a basic example of how you might implement a shared WebDriver using a base class:
```java
public class DriverBase {
private static WebDriver driver;
public static WebDriver getDriver() {
if (driver == null) {
// Initialize the WebDriver instance here (e.g., new ChromeDriver())
driver = new ChromeDriver();
}
return driver;
}
@AfterAll
public static void tearDown() {
if (driver != null) {
driver.quit();
driver = null;
}
}
}
```
In your step definition files, you would then use `DriverBase.getDriver()` to obtain the WebDriver instance.
By following these steps, you should be able to manage a single WebDriver instance across multiple feature files and step definition files, preventing multiple browsers from being invoked during your test execution.
Remember to also review your Cucumber configuration to ensure it aligns with these changes
Let me know how it goes..
Thanks for the reply, I will try this
Hi Raghav, Thank you for valuable knowledge, I have one one question after applying some steps in my background keyword in my console not showing answer like your answer I my console showing background (steps from background) the my scenario again background and scenario
Example..
Background:
Given a registered user exists
Given user is on Amazon login page
When user enters user name
And user enters password
And user click on login button
Then user navigate to order page
Scenario: Check open order details
When User click on open order link
Then user check open order details
Background:
Given a registered user exists
Given user is on Amazon login page
When user enters user name
And user enters password
And user click on login button
Then user navigate to order page
Scenario: Check Cancelled order details
When User click on Cancelled order link
Then user check Cancelled order details
What should i do for this i want answer like your answer?? Plz help me.
Hi Jitender, pls check again the steps and setup. Not sure why it will be different if you follow the same steps
@@RaghavPal Hi Raghav I saw your first video again slowly then I found my mistake now I have corrected that issue and code is running properly, Thank you for your help and reply in early morning
Hi Raghav,
When I run the feature file, I am getting the warning "You are using deprecated Main class. Please use io.cucumber.core.cli.Main" along with an exception "java.util.concurrent.ExecutionException". The code snippets aren't displayed in the console once I've run the feature file. It only displays
"0 Scenarios
0 Steps
0m0.302s"
Can you please help me on this?
Hi Ishwarya, you can continue with this, this is seen by many users, pls check other comments of this video
@@RaghavPal Thank you for the prompt response, Raghav.
Hello sir, cucumber is not generating index.html report after execution. plz suggest
Hi Ankush, pls refresh the reports folder and check again, pls check if you have done all the setup and all required dependencies are added, Can check changing the ver
What if, i run the scenario using tag. Will background going to get executed before my scenario attached to that tag ?
Hi will need to check
Hey hai.. do you know how to use TestNG in cucumber framework
I will check if I have videos on it or will make it, you can do it
Can we pass login credentials in the background as parameters?
You can try Shirantha
Sir pls try to cover all the topics in cucumber
I will do Ilavarasan, will also create a serives on Basics of BDD
@@RaghavPal Tq sir
@Raghav : Can you please let me know what is pretty report in Test Runner
Hi Tulasi, in cucumber Pretty Format generates the Cucumber test report in the HTML format, i.e. an HTML file. It is the most readable report format. It generates the report in the same way as it is a feature file, so tracing is also made easy.
@@RaghavPal But I see there is an XML for pretty report. What about this XML report. I am thinking that pretty generates XML report. Correct me if I am wrong
Ok, It may be to add some formatting to make it more presentable. I will need to check more online, Let me know if you find out on this
@@RaghavPal Actually I am looking for this information. Just wanted to check with you if you have any idea on this.
What is the difference between Background and Hooks?
Hi Mojtaba, Background is used to set up a precondition
Background runs before each scenario, but after any Before hooks. This will help www.numpyninja.com/post/hooks-vs-background-cucumber#:~:text=After%20hooks%20will%20be%20run,undefined%2C%20pending%20or%20skipped%20steps.&text=Background%20is%20used%20to%20set,but%20after%20any%20Before%20hooks.
but if i have a lot of . feature background will be repeated in every.feature ?
can discuss your scenario in detail
Hii please tell us what happens if background step fails in cucumber??
Hi Samir, can check this discussion - github.com/jenkinsci/cucumber-reports-plugin/issues/65
Hi May I know where in git this project is added so that I can download?
github.com/Raghav-Pal/SeleniumJavaFramework1
Hello Raghav how can we pass test data in background tag i have one scenario which repeated so decided to used background but with statement i have to pass test data can you give any reference i tried it but it not work. please any who can help me in this.
Pawan
When using Cucumber with Selenium Java, the `Background` section in your feature file allows you to define common steps that run before each scenario within that feature. However, passing test data directly into the `Background` section is not directly supported. The `Background` steps are meant to set up the initial state of the system under test and should not change for each scenario
That said, there are a few approaches you can take to achieve your goal:
1. Predefined Data in Background Steps:
- Define your test data (e.g., usernames, passwords, search queries) as constants or variables in your step definitions.
- In the `Background` section, use these predefined values for common steps (e.g., logging in).
- Example:
```gherkin
Feature: Test Background
Background:
Given User is Logged In
And User has a valid product in the cart
Scenario: Search a product and add it to the cart
When User searches for a product
And adds the product to the cart
Then the cart should display the added item
```
2. Scenario Outline with Examples:
- If your repeated scenario involves variations of the same steps with different data, consider using a `Scenario Outline` with an `Examples` table.
- Example:
```gherkin
Feature: Test Background
Background:
Given User is Logged In
Scenario Outline: Search a product and add it to the cart
When User searches for ""
And adds the product to the cart
Then the cart should display the added item
Examples:
| product |
| Lenovo Laptop |
| iPhone |
```
3. Data Tables in Steps:
- If you need dynamic data for each scenario, use data tables within your steps.
- Example:
```gherkin
Feature: Test Background
Background:
Given User is Logged In
Scenario: Search a product and add it to the cart
When User searches for a product
And adds the product "" to the cart
Then the cart should display the added item
Examples:
| product |
| Lenovo Laptop |
| iPhone |
```
- In your step definitions, extract the data from the data table:
```java
@When("^User searches for a product$")
public void user_searches_for_product(DataTable dataTable) {
List data = dataTable.asMaps(String.class, String.class);
String product = data.get(0).get("product");
// Perform search based on the product
}
```
Remember that the `Background` section is primarily for setting up the context, and dynamic test data should be handled within the individual scenarios. Choose the approach that best fits your requirements and keeps your feature files clean and maintainable
--
How can we do the parameterization for user the user name and password for the backgound here?
Trilekhya
Here's how to parameterize username and password for background steps in Selenium Cucumber:
1. Define Parameters in Feature File:
- Use angle brackets `` to specify parameters in your Background steps:
```gherkin
Background:
Given I am on the login page
When I enter username as "" and password as ""
And I click on the login button
```
2. Pass Values from Step Definitions:
- Use the `Scenario` object to retrieve parameter values from the feature file:
```java
@Given("^I am on the login page$")
public void i_am_on_the_login_page() {
driver.get("your-login-page.com");
}
@When("^I enter username as \"([^\"]*)\" and password as \"([^\"]*)\"$")
public void i_enter_username_and_password(String username, String password) {
WebElement usernameField = driver.findElement(By.id("username"));
usernameField.sendKeys(username);
WebElement passwordField = driver.findElement(By.id("password"));
passwordField.sendKeys(password);
driver.findElement(By.id("login_button")).click();
}
```
3. Manage Parameter Values:
- Data Tables: Store values in a data table within the feature file:
```gherkin
Examples:
| username | password |
| user1@example.com | password123 |
| user2@example.com | password456 |
```
- External Files: Load values from external sources like CSV files or config files.
- Hook Implementations: Use Hooks (e.g., `@Before`) to fetch values from databases or APIs.
4. Access Parameters in Background Steps:
- Parameters defined in the Feature file are available to Background steps as well as individual scenarios.
Additional Considerations:
- Parameter Type Flexibility: Cucumber supports various parameter types (e.g., numbers, lists, custom objects).
- Organization and Reusability: Consider organizing parameters in separate files or shared resources for better maintainability.
- Security: Handle sensitive information like passwords with care, using encryption or environment variables.
@@RaghavPal , I am getting the error at Examples, saying "Found examples when expecting one of: [comment, doc_string, row, scenario, scenario_outline, step, tag]. (Current state: step).". How to fix this?
Trilekhya
Common Causes and Solutions:
1. Incorrect Placement of Examples:
- Ensure the `Examples:` keyword is placed directly after the `Scenario Outline:` keyword, with a blank line separating them.
- Example:
```gherkin
Scenario Outline: Login with different credentials
Given I am on the login page
When I enter and
And I click the login button
Then I should be redirected to the dashboard
Examples:
| username | password |
| user1 | password1 |
| user2 | password2 |
```
2. Missing Blank Line:
- Verify that there's a blank line between the `Scenario Outline:` and `Examples:` keywords.
3. Incorrect Indentation:
- Maintain proper indentation:
- `Scenario Outline:` and `Examples:` should be flush left.
- Steps and table rows should be indented one level.
4. Missing Step Definitions:
- Ensure you have matching step definitions in your Java code for all steps in your feature file.
5. Cucumber Version Incompatibility:
- Check for compatibility issues between your Cucumber version and Gherkin syntax.
- Consider updating Cucumber if necessary.
Additional Troubleshooting Tips:
- Review Feature File Syntax: Carefully examine your feature file for any structural errors or typos.
- Check Glue Code: Ensure your step definitions are correctly implemented in your Java code.
- Consult Documentation: Refer to Cucumber's documentation for specific guidelines and examples.
- Utilize IDE Help: If using an IDE, leverage its syntax highlighting and validation features to identify errors.
- Run in Debug Mode: Debugging can reveal details about the error's origin.
What if the user uses background and before hooks together?
Hi Aniketh,
ccording to the Cucumber documentation, here is what Before does:
Before hooks will be run before the first step of each scenario. They will run in the same order of which they are registered.
And here is what Background does:
Background allows you to add some context to the scenarios in a single feature. A Background is much like a scenario containing a number of steps. The difference is when it is run. The background is run before each of your scenarios but after any of your Before Hooks.
In facts, as you noticed already, their structures are a little bit different. The common practice is to use them as follows:
Use Background when you provide customer-readable pre-conditions to your scenarios
Use Before when you have to do some technical setup before your scenarios
But the main thing to understand here is the order of the operations:
Before Hook 1 -> Before Hook 2 -> ... -> Background -> Scenario
They just represent different levels of pre-conditions.
stackoverflow.com/questions/37585052/cucumber-whats-the-difference-between-background-and-before-tag
Can we used more feature keyword in one feature file.
Yes you can Prachi