JBehave如何使用Java?

Ral*_*lph 5 bdd jbehave selenium-webdriver

我有一项工作任务似乎无法完成,因为我没有完全掌握工具集.我应该使用JBehave和Selenium Web Driver来将某本书添加到亚马逊帐户的心愿单上.我有一个给定的故事,我应该使用前面提到的工具用于"学习目的".我知道JBehave是BDD的框架.所以,我有一些我想测试的故事.然而,令我困惑的是配置和"步骤定义"部分,我没有真正得到.我的问题是我真的不明白如何让所有这些部分一起工作.Selenium WebDriver在哪个方面适合?请注意,我已经使用Selenium和Java,这是一件轻而易举的事.

我想以gherkin格式给你一个故事的例子,我很欣赏这个主题的任何见解,也许是对所有部分如何组合起来的澄清.

Given user <username> with password <password> has a valid amazon.com account
And has a wish list
And wants to purchase book <title> at a later date
When a request to place the book in the wish list is made
Then the book is placed in the wish list
And the book <title> appears in the wish list when <username> logs in at a later date.
Run Code Online (Sandbox Code Playgroud)

Bri*_* S. 3

现在您有了故事,您需要步骤。步骤是将由故事执行的 Java 代码。故事中的每一行都映射到一个 Java 步骤。请参阅有关候选步骤的文档。

这是对您的故事和步骤的简单介绍。但它至少应该让您了解故事和步骤如何联系在一起。

故事

Given user username with password passcode is on product page url
When the user clicks add to wish list
Then the wish list page is displayed  
And the product title appears on the wish list 
Run Code Online (Sandbox Code Playgroud)

脚步

public class WishlistSteps {
  WebDriver driver = null;

  @BeforeScenario
  public void scenarioSetup() {
    driver = new FirefoxDriver;
  }

  @Given("user $username with password $passcode is on product page $url")
  public void loadProduct(String username, String passcode, String url) {
    doUserLogin(driver, username, passcode); // defined elsewhere
    driver.get(url);
  }

  @When("the user clicks add to wishlist")
  public void addToWishlist() {
    driver.findElement(By.class("addToWishlist")).click();
  }

  @Then("the wish list page is displayed")
  public void isWishlistPage() {
    assertTrue("Wishlist page", driver.getCurrentUrl().matches(".*/gp/registry/wishlist.*"));
  } 

  @Then("the product $title appears on the wish list")
  public void checkProduct(String title) {
    // check product entries
    // assert if product not found
  }

  @AfterScenario
  public void afterScenario() {
    driver.quit();
  }
}
Run Code Online (Sandbox Code Playgroud)

接下来,您将需要一个实际查找并运行故事的运行程序。请参阅有关运行故事的文档。下面是一个非常简单的运行器,它将作为 JUnit 测试运行。

跑步者

public class JBehaveRunner extends JUnitStories {
  public JBehaveRunner() {
    super();
  }

  @Override
  public injectableStepsFactory stepsFactory() {
    return new InstanceStepsFactory( configuration(),
      new WishlistSteps() );
  }

  @Override
  protected List<String> storyPaths() {
    return Arrays.asList("stories/Wishlist.story");
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,该运行程序将作为 JUnit 测试执行。您可以配置 IDE 来运行它,或者使用 Maven 或 Gradle(取决于您的设置)。

mvn test
Run Code Online (Sandbox Code Playgroud)

我发现下面的页面提供了整个设置的详细概述。JBhave 存储库中的示例也很有用。