简体   繁体   中英

Get Cucumber-jvm step as String in java

I have written the following scenario in gherkin

  Scenario: Correct login should take the user to the next screen
  Given User is on the login screen
  When User enters username as "Donald"
  And User enters password as "Trump"
  And User clicks the login button
  Then User should be taken to the next screen

And I have the following step mapped in cucumber-jvm to this scenario

 ...
 @Given("^User is on the login screen$)
 public void goToLoginScreen(){
    //some logic
 }

How to get the content inbetween the @Given annotation inside the mapped step definition method. I have a couple of use cases where this would be helpful but am not able to find out how so far.

Include the whole step in brackets. This will be the first captured group.

@Given("^(User is on the login screen)$)
 public void goToLoginScreen(String stepText){
    System.out.println(stepText);
    //some logic
 }

You can use capture groups to capture variables in your steps. For example:

 @When("^User enters username as (.*)$")
 public void entersUsernameAs(String username){
    //some logic
 }

You can also use multiple variables in a step. For example:

 @Given("^User logs in as (.*) with password (.*)$")
 public void usersLogsInAs(String username, String password){
    //go to loginpage
    //enter username
    //enter password
    //click login button
 }

You can use different capture groups. I usually use (.*) for a String that could be anything and (\\\\d+) for integers. You can also use (option|other|else) for a limited set of strings (in this example "option" , "other" and "else" ) which will only match steps using those strings rather than any string like (.*) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM