Cucumber BDD is a test automation framework like TestNG, but it is designed to strictly follow BDD rules. The Cucumber framework was earlier developed in Python and after its success with Python, it is later released for Java as well.
For Cucumber-Java, you can add below dependencies to your maven project.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
If you are using Gradle, you can use below dependencies.
compile 'info.cukes:cucumber-java:1.2.5'
compile 'junit:junit:4.12'
Also, you can checkout ready skeleton project from Github: https://github.com/cucumber/cucumber-java-skeleton
Once you have setup project, you can start writing your feature files. It should be of Gherkin format.
Example:
Feature: Login Functionality
Verifying the login functionality of the site.
Scenario: Login
Given I go to https://softwaretestingboard.com/qna
When I log in using Username as âUSERâ and Password âPASSWORDâ
Then I should see logged in
Scenario: Invalid Login
Given I go to https://softwaretestingboard.com/qna
When I log in using Username as âUSER1â and Password ââ
Then I should see error message
You create step definitions file in Java accordingly.
public class stepDefinition {
WebDriver dr;
@Given("^I go to \"(.*)\"$")
public void navigate(String URL){
dr=new FirefoxDriver();
dr.get(URL);
}
@When ("^I log in using username as \"(.*)\" and password as \"(.*)\"$")
public void login(String username,String password){
dr.findElement(By.xpath("//*[@id="site-header"]/div/a[4]/span")).click();
dr.findElement(By.xpath("//*[@id="qa-userid"]")).sendKeys(username);
dr.findElement(By.xpath("//*[@id="qa-password"]")).sendKeys(password);
dr.findElement(By.xpath("//*[@id="qa-login"]")).click();
dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
@Then("^I should see error message$")
public void verifySuccessful(){
String loginTxt = dr.findElement(By.xpath("//*[@id="site-header"]/div/a[4]/span")).getText();
Assert.assertTrue("Login not successful","".equals(loginTxt));
}
@Then("^Then I should be logged in ")
public void verifySuccessful(){
String loginTxt = dr.findElement(By.xpath("//*[@id="site-header"]/div/a[4]/span")).getText();
Assert.assertTrue("Login successful!","".equals(loginTxt));
}
}
Here is your JUnit Runner to run your Cucumber feature files.
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@Cucumber.Options(format={"SimpleHtmlReport:report/sampleTest.html"},tags={"@sampleTest"})
Public class JUnitRunner {
}
You can right click on JUnit runner and run your code as JUnit.
Comment below or ask a new question if you need more information.