Monday, 30 April 2018

Gherkin: Escaping character (/)

Since Gherkin support regular expressions, characters like $, *, . has special meaning. If your scenario steps has these special characters, then you should use escaping character.

Ex
When I purchased for $100

Above step can be written like below.

@When("I purchased for \\$(100)")

As you observer above snippet, I defined $ like \\$ in java code.

Find the below working application.

PurchaseOrder.feature
Feature: Give special discount to the users 

Scenario: Give 10% percent discount on 100$ purchase 

 Given As a customer of the company 
 When I purchased for $100 
 Then I should get 10 percentage discount 

PurchaseOrderTest.java

package com.sample.test;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class PurchaseOrderTest {

 @Given("As a customer of the company")
 public void as_a_customer_of_the_company() throws Exception {
  System.out.println("I am the customer of the company");
 }

 @When("I purchased for \\$(100)")
 public void i_purchased_for_$(int arg1) throws Exception {
  System.out.println("Purchased for " + arg1 + "$");
 }

 @Then("I should get (10) percentage discount")
 public void i_should_get_percentage_discount(int arg1) throws Exception {
  System.out.println("I got " + arg1 + " percentage of discount");
 }

}


TestRun.java

package com.sample.main;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(monochrome = true, features = "src/test/java/com/sample/features", glue = "com.sample.test", plugin = {
  "pretty" })
public class TestRun {

}

When you ran TestRun.java, you can able to see below kind of output.

Feature: Give special discount to the users

  Scenario: Give 10% percent discount on 100$ purchase # src/test/java/com/sample/features/PurchaseOrder.feature:3
I am the customer of the company
    Given As a customer of the company                 # PurchaseOrderTest.as_a_customer_of_the_company()
Purchased for 100$
    When I purchased for $100                          # PurchaseOrderTest.i_purchased_for_$(int)
I got 10 percentage of discount
    Then I should get 10 percentage discount           # PurchaseOrderTest.i_should_get_percentage_discount(int)

1 Scenarios (1 passed)
3 Steps (3 passed)
0m0.250s




Previous                                                 Next                                                 Home

Gherkin: Internationalisation support

Cucumber supports 40+ langauges. You can write the .feature file in any of the language. But you need to specify the language that you are using by putting ‘#langauge’ as the first line of the .feature file.

How to get all the langauges supported by Gherkin?
Copy all the cucumber relevant jars into a directory called ‘jars’.

For example, I copied below jars to 'jars' directory.
cucumber-core-2.3.1.jar
gherkin-5.0.0.jar

Go to the parent directory of 'jars' directory and run below command.
java -cp "cucumber_jars/*;." cucumber.api.cli.Main --i18n help

C:\Users\krishna\Documents\Study\cucumber>java -cp "cucumber_jars/*;." cucumber.api.cli.Main --i18n help
af
am
ar
ast
az
bg
bm
bs
ca
cs
cy-GB
da
de
el
em
en
en-Scouse
en-au
en-lol
en-old
en-pirate
eo
es
et
fa
fi
fr
ga
gj
gl
he
hi
hr
ht
hu
id
is
it
ja
jv
ka
kn
ko
lt
lu
lv
mk-Cyrl
mk-Latn
mn
nl
no
pa
pl
pt
ro
ru
sk
sl
sr-Cyrl
sr-Latn
sv
ta
th
tl
tlh
tr
tt
uk
ur
uz
vi
zh-CN
zh-TW


How to get the language codes associated with specific language?
Below command return all the keywords associated with language code id.
java -cp "cucumber_jars/*;." cucumber.api.cli.Main --i18n id

C:\Users\krishna\Documents\Study\cucumber>java -cp "cucumber_jars/*;." cucumber.api.cli.Main --i18n id
      | feature          | "Fitur"           |
      | background       | "Dasar"           |
      | scenario         | "Skenario"        |
      | scenario outline | "Skenario konsep" |
      | examples         | "Contoh"          |
      | given            | "* ", "Dengan "   |
      | when             | "* ", "Ketika "   |
      | then             | "* ", "Maka "     |
      | and              | "* ", "Dan "      |
      | but              | "* ", "Tapi "     |
      | given (code)     | "Dengan"          |
      | when (code)      | "Ketika"          |
      | then (code)      | "Maka"            |
      | and (code)       | "Dan"             |
      | but (code)       | "Tapi"            |


For example, below feature file is written in Indonesian language. You can observe I added #language statement at first line.

Login.feature

#language: id
# This feature checks the login flow of the user.

Fitur: Login

    Login should be quick and friendly. When user logged in with correct credentials, then he would be greeted with welcome message.
    If user session is expired, he should be reverted back to login page.

    # Check the happy Scenario  
    Skenario: Successful Login 
    User should be logged in successfully by providing correct username and password.
            
        Dengan I am registered user to the application 
        Ketika I log in with user name "krishna" and password "password123" 
        Maka I should be logged in successfully 
        Dan I should see a personalized greeting message 
    
    # Checks session expiration scenarion
    Skenario: Session Expired 
    User should be redirected to login page on session expiration
    
        Dengan I am the logged in user to the application 
        Tapi My session is expired 
        Ketika I try to interact with the application 
        Maka I should be notified about session expiration 
        Dan I should be redirected to the login page

When I generate the code using cucumber, it generates below skelton.

@Dengan("^I am registered user to the application$")
public void iAmRegisteredUserToTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Ketika("^I log in with user name \"([^\"]*)\" and password \"([^\"]*)\"$")
public void iLogInWithUserNameAndPassword(String arg1, String arg2) throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Maka("^I should be logged in successfully$")
public void iShouldBeLoggedInSuccessfully() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Maka("^I should see a personalized greeting message$")
public void iShouldSeeAPersonalizedGreetingMessage() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Dengan("^I am the logged in user to the application$")
public void iAmTheLoggedInUserToTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Dengan("^My session is expired$")
public void mySessionIsExpired() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Ketika("^I try to interact with the application$")
public void iTryToInteractWithTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Maka("^I should be notified about session expiration$")
public void iShouldBeNotifiedAboutSessionExpiration() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Maka("^I should be redirected to the login page$")
public void iShouldBeRedirectedToTheLoginPage() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}


Previous                                                 Next                                                 Home

Gherkin: Adding comments to the feature file

Comments are used to document more information.

Comments in Gherkin are written using pound (#) symbol.

Login.feature

# This feature checks the login flow of the user.

Feature: Login

 Login should be quick and friendly. When user logged in with correct credentials, then he would be greeted with welcome message.
 If user session is expired, he should be reverted back to login page.

 # Check the happy Scenario 
 Scenario: Successful Login 
 User should be logged in successfully by providing correct username and password.
   
  Given I am registered user to the application 
  When I log in with user name "krishna" and password "password123" 
  Then I should be logged in successfully 
  And I should see a personalized greeting message 
 
 # Checks session expiration scenarion
 Scenario: Session Expired 
 User should be redirected to login page on session expiration
 
  Given I am the logged in user to the application 
  But My session is expired 
  When I try to interact with the application 
  Then I should be notified about session expiration 
  And I should be redirected to the login page

Cucumber generates below java code.

@Given("^I am registered user to the application$")
public void iAmRegisteredUserToTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@When("^I log in with user name \"([^\"]*)\" and password \"([^\"]*)\"$")
public void iLogInWithUserNameAndPassword(String arg1, String arg2) throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I should be logged in successfully$")
public void iShouldBeLoggedInSuccessfully() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I should see a personalized greeting message$")
public void iShouldSeeAPersonalizedGreetingMessage() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^I am the logged in user to the application$")
public void iAmTheLoggedInUserToTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^My session is expired$")
public void mySessionIsExpired() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@When("^I try to interact with the application$")
public void iTryToInteractWithTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I should be notified about session expiration$")
public void iShouldBeNotifiedAboutSessionExpiration() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I should be redirected to the login page$")
public void iShouldBeRedirectedToTheLoginPage() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}



Previous                                                 Next                                                 Home

Sunday, 29 April 2018

Gherkin: Background: Mention common steps

In real world application, many scenarios can share common steps. Instead of writing these steps redundantly, we can place these common steps in background section and reuse them.

Let’s see it by an example.
 Scenario: Password should be reset successfully
  Given I  am a logged in user
  When I choose to reset password
  And provided current password "password123"
  And provided new password "password3456"
  Then if the current password & new password are not same, password should be reset successfully
  
 Scenario: Password reset failure case
  Given I  am a logged in user
  When I choose to reset password
  And provided current password "password123"
  And provided new password "password123"
  Then if the current password & new password are same, password should not be reset
  And user should be notified

As you see above scenarios, first 3 steps are common in both these scenarios. We can move these three steps into background section and reuse.

Find the below working example.

PasswordReset.feature

Feature: Testing reset password functionality

 Background: Common steps for password reset scenario
  Given I  am a logged in user
  When I choose to reset password
  And provided current password "password123"

 Scenario: Password should be reset successfully
  When provided new password "password3456"
  Then if the current password & new password are not same, password should be reset successfully
  
 Scenario: Password reset failure case
  When provided new password "password123"
  Then if the current password & new password are same, password should not be reset
  And user should be notified

Passwordutil.java

package com.sample.util;

public class PasswordUtil {

 public static boolean resetPassword(String currentPassword, String newPassword) {
  if (currentPassword.equals(newPassword)) {
   return false;
  }

  return true;
 }
}

PasswordResetTest.java

package com.sample.test;

import com.sample.util.PasswordUtil;

import cucumber.api.java.en.*;
import static org.junit.Assert.*;

public class PasswordResetTest {
 private String currentPassword;
 private String newPassword;

 @Given("^I  am a logged in user$")
 public void i_am_a_logged_in_user() throws Exception {
  System.out.println("User is getting logged in");
 }

 @When("^I choose to reset password$")
 public void i_choose_to_reset_password() throws Exception {
  System.out.println("User choose to reset password");
 }

 @When("^provided current password \"([^\"]*)\"$")
 public void provided_current_password(String arg1) throws Exception {
  System.out.println("Reading current password");
  this.currentPassword = arg1;
 }

 @When("^provided new password \"([^\"]*)\"$")
 public void provided_new_password(String arg1) throws Exception {
  System.out.println("Reading new password");
  this.newPassword = arg1;
 }

 @Then("^if the current password & new password are not same, password should be reset successfully$")
 public void if_the_current_password_new_password_are_not_same_password_should_be_reset_successfully()
   throws Exception {
  boolean isResetSuccessful = PasswordUtil.resetPassword(currentPassword, newPassword);
  assertTrue("Password reset successful", isResetSuccessful);
  System.out.println("Password reset successful");
 }

 @Then("^if the current password & new password are same, password should not be reset$")
 public void if_the_current_password_new_password_are_same_password_should_not_be_reset() throws Exception {
  boolean isResetSuccessful = PasswordUtil.resetPassword(currentPassword, newPassword);
  assertFalse("Password reset can't happen, since both current, new passwords are same", isResetSuccessful);
  System.out.println("Password reset can't happen, since both current, new passwords are same");
 }

 @Then("^user should be notified$")
 public void user_should_be_notified() throws Exception {
  System.out.println("New passowrd shouldn't be equal to current password");
 }

}


TestRun.java

package com.sample.main;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(monochrome = true, features = "src/test/java/com/sample/features", glue = "com.sample.test", plugin = {
  "pretty" })
public class TestRun {

}


When you run above application, you can able to see below messages in console.

Feature: Testing reset password functionality

  Background: Common steps for password reset scenario # src/test/java/com/sample/features/PasswordReset.feature:3
User is getting logged in
    Given I  am a logged in user                       # PasswordResetTest.i_am_a_logged_in_user()
User choose to reset password
    When I choose to reset password                    # PasswordResetTest.i_choose_to_reset_password()
Reading current password
    And provided current password "password123"        # PasswordResetTest.provided_current_password(String)

  Scenario: Password should be reset successfully                                                   # src/test/java/com/sample/features/PasswordReset.feature:8
Reading new password
    When provided new password "password3456"                                                       # PasswordResetTest.provided_new_password(String)
Password reset successful
    Then if the current password & new password are not same, password should be reset successfully # PasswordResetTest.if_the_current_password_new_password_are_not_same_password_should_be_reset_successfully()

  Background: Common steps for password reset scenario # src/test/java/com/sample/features/PasswordReset.feature:3
User is getting logged in
    Given I  am a logged in user                       # PasswordResetTest.i_am_a_logged_in_user()
User choose to reset password
    When I choose to reset password                    # PasswordResetTest.i_choose_to_reset_password()
Reading current password
    And provided current password "password123"        # PasswordResetTest.provided_current_password(String)

  Scenario: Password reset failure case                                                # src/test/java/com/sample/features/PasswordReset.feature:12
Reading new password
    When provided new password "password123"                                           # PasswordResetTest.provided_new_password(String)
Password reset can't happen, since both current, new passwords are same
    Then if the current password & new password are same, password should not be reset # PasswordResetTest.if_the_current_password_new_password_are_same_password_should_not_be_reset()
New passowrd shouldn't be equal to current password
    And user should be notified                                                        # PasswordResetTest.user_should_be_notified()

2 Scenarios (2 passed)
11 Steps (11 passed)
0m0.267s


Previous                                                 Next                                                 Home

Gherkin: * keyword

You can replace the keywords But, Given, When, Then, And with a ‘*’. It is another way of writing, but to the cucumber both the styles are same.

Example1
Scenario: Successful Login 
 User should be logged in successfully by providing correct username and password.
  
 Given I am registered user to the application 
 When I log in with user name "krishna" and password "password123" 
 Then I should be logged in successfully 
 And I should see a personalized greeting message

Above scenario can be written like below.

Scenario: Successful Login 
 User should be logged in successfully by providing correct username and password.
  
 * I am registered user to the application 
 * I log in with user name "krishna" and password "password123" 
 * I should be logged in successfully 
 * I should see a personalized greeting message

Example 2
Scenario: Session Expired 
 User should be redirected to login page on session expiration
 
 Given I am the logged in user to the application 
 But My session is expired 
 When I try to interact with the application 
 Then I should be notified about session expiration 
 And I should be redirected to the login page 

Above scenario can be written like below.

Scenario: Session Expired 
 User should be redirected to login page on session expiration
 
 * I am the logged in user to the application 
 * My session is expired 
 * I try to interact with the application 
 * I should be notified about session expiration 
 * I should be redirected to the login page


I personally I preferred the approach of using the keyword When, Then, But, And keywords. You can choose either of the approaches.

Login.feature

Feature: Login 

 Login should be quick and friendly. When user logged in with correct credentials, then he would be greeted with welcome message.
 If user session is expired, he should be reverted back to login page.
 
Scenario: Successful Login 
 User should be logged in successfully by providing correct username and password.
  
 * I am registered user to the application 
 * I log in with user name "krishna" and password "password123" 
 * I should be logged in successfully 
 * I should see a personalized greeting message
 
Scenario: Session Expired 
 User should be redirected to login page on session expiration
 
 * I am the logged in user to the application 
 * My session is expired 
 * I try to interact with the application 
 * I should be notified about session expiration 
 * I should be redirected to the login page

Cucumber generates below snippet.

@Given("^I am registered user to the application$")
public void iAmRegisteredUserToTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^I log in with user name \"([^\"]*)\" and password \"([^\"]*)\"$")
public void iLogInWithUserNameAndPassword(String arg1, String arg2) throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^I should be logged in successfully$")
public void iShouldBeLoggedInSuccessfully() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^I should see a personalized greeting message$")
public void iShouldSeeAPersonalizedGreetingMessage() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^I am the logged in user to the application$")
public void iAmTheLoggedInUserToTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^My session is expired$")
public void mySessionIsExpired() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^I try to interact with the application$")
public void iTryToInteractWithTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^I should be notified about session expiration$")
public void iShouldBeNotifiedAboutSessionExpiration() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^I should be redirected to the login page$")
public void iShouldBeRedirectedToTheLoginPage() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}



Previous                                                 Next                                                 Home

Gherkin: And, Then keywords

And, Then keywords are used to combine the statements.

Example1
Scenario: Successful Login 
 User should be logged in successfully by providing correct username and password.
  
 Given I am registered user to the application 
 When I log in with user name "krishna" and password "password123" 
 Then I should be logged in successfully 
 And I should see a personalized greeting message

Example 2
Scenario: Session Expired 
 User should be redirected to login page on session expiration
 
 Given I am the logged in user to the application 
 But My session is expired 
 When I try to interact with the application 
 Then I should be notified about session expiration 
 And I should be redirected to the login page

Login.feature
Feature: Login 

 Login should be quick and friendly. When user logged in with correct credentials, then he would be greeted with welcome message.
 If user session is expired, he should be reverted back to login page.
 
Scenario: Successful Login 
 User should be logged in successfully by providing correct username and password.
  
 Given I am registered user to the application 
 When I log in with user name "krishna" and password "password123" 
 Then I should be logged in successfully 
 And I should see a personalized greeting message 
 
Scenario: Session Expired 
 User should be redirected to login page on session expiration
 
 Given I am the logged in user to the application 
 But My session is expired 
 When I try to interact with the application 
 Then I should be notified about session expiration 
 And I should be redirected to the login page 

Cucumber generates below Skelton to above feature file.

@Given("^I am registered user to the application$")
public void iAmRegisteredUserToTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@When("^I log in with user name \"([^\"]*)\" and password \"([^\"]*)\"$")
public void iLogInWithUserNameAndPassword(String arg1, String arg2) throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I should be logged in successfully$")
public void iShouldBeLoggedInSuccessfully() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I should see a personalized greeting message$")
public void iShouldSeeAPersonalizedGreetingMessage() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^I am the logged in user to the application$")
public void iAmTheLoggedInUserToTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Given("^My session is expired$")
public void mySessionIsExpired() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@When("^I try to interact with the application$")
public void iTryToInteractWithTheApplication() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I should be notified about session expiration$")
public void iShouldBeNotifiedAboutSessionExpiration() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

@Then("^I should be redirected to the login page$")
public void iShouldBeRedirectedToTheLoginPage() throws Exception {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}




Previous                                                 Next                                                 Home