Search by

Selenium with JBehave

Your guide to running Selenium Webdriver tests with JBehave on BrowserStack.

JBehave repo on Github


BrowserStack gives you instant access to our Selenium Grid of 2000+ real devices and desktop browsers. Running your Selenium tests with JBehave on BrowserStack is simple. This guide will help you:

  1. Run your first test
  2. Mark tests as pass / fail
  3. Debug your app


Before you can start running your Selenium tests with JBehave, ensure you have the JBehave libraries installed. Ensure it is included in the pom.xml, as shown below:

<!-- Install using maven -->

Run your first test

To understand how to integrate with BrowserStack, we will look at two things:

  1. A sample test case written in JBehave with Java
  2. Integration of this sample test case with BrowserStack

Sample test case

The sample JBehave test case below searches for the string “BrowserStack” on Google, and checks if the title of the resulting page is “BrowserStack - Google Search”

// Google Story
Scenario: Google Search Functionality

When I type query as "BrowserStack"
Then I submit
Then I should see title "BrowserStack - Google Search"

We also need the Page, Steps definition and the Embedder.

// Google Page
public class GooglePage {
    private String DEFAULT_GOOGLE_URL = "";
    private WebDriver driver;
    private WebElement element;

    public GooglePage(WebDriver driver) {
       this.driver = driver;

    public String getTitle(){
        return driver.getTitle();

    public void searchOnGoogle(String keyword) {
        element = driver.findElement("q"));

    public void submitSearch() throws Exception {
// Google Steps
public class GoogleSteps {
    private GooglePage page;

    public GoogleSteps(WebDriver driver) {
       page = new GooglePage(driver);

    @When("I type query as \"$keyword\"")
    public void searchGoogle(String keyword) {

    @Then("I submit")
    public void submit() throws Exception {

    @Then("I should see title \"$keyword\"")
    public void titleShouldContain(String keyword) {
        Assert.assertEquals(keyword, page.getTitle());
// Embedder
public class SingleEmbedder extends Embedder {
    private WebDriver driver;

    public SingleEmbedder(WebDriver driver) {
        this.driver = driver;

    public EmbedderControls embedderControls() {
        return new EmbedderControls().doIgnoreFailureInStories(true).doIgnoreFailureInView(true);

    public Configuration configuration() {
        Class<? extends SingleEmbedder> embedderClass = this.getClass();
        return new MostUsefulConfiguration()
            .useStoryLoader(new LoadFromClasspath(embedderClass.getClassLoader()))
            .useStoryReporterBuilder(new StoryReporterBuilder()
                .withCrossReference(new CrossReference()))
            .useParameterConverters(new ParameterConverters()
                .addConverters(new DateConverter(new SimpleDateFormat("yyyy-MM-dd"))))
            .useParameterControls(new ParameterControls().useNameDelimiterLeft("<").useNameDelimiterRight(">"))
            .useStepPatternParser(new RegexPrefixCapturingPatternParser(
            .useStepMonitor(new SilentStepMonitor());

    public InjectableStepsFactory stepsFactory() {
        return new InstanceStepsFactory(configuration(), new GoogleSteps(driver));


Once we have defined the test case, we are ready to integrate this JBehave test case into BrowserStack.

Integrating with BrowserStack

Note: Running your Selenium tests on BrowserStack requires a BrowserStack Username and Access Key.

To obtain your username and access keys, sign up for a Free Trial or purchase a plan.

We can now integrate our JBehave test case into BrowserStack. To start, we define a class which contains the methods to configure and create the connection with BrowserStack.

public class BrowserStackJBehaveRunner {

    public WebDriver driver;
    private Local l;

    private static JSONObject config;

    @Parameter(value = 0)
    public int taskID;

    public static Collection<Object[]> data() throws Exception {
        JSONParser parser = new JSONParser();
        config = (JSONObject) parser.parse(new FileReader("src/test/resources/conf/" + System.getProperty("config")));
        int envs = ((JSONArray)config.get("environments")).size();

        List<Object[]> taskIDs = new ArrayList<Object[]>();
        for(int i=0; i<envs; i++) {
            taskIDs.add(new Object[] {i});

        return taskIDs;

    public void setUp() throws Exception {
        JSONArray envs = (JSONArray) config.get("environments");

        DesiredCapabilities capabilities = new DesiredCapabilities();

        Map<String, String> envCapabilities = (Map<String, String>) envs.get(taskID);
        Iterator it = envCapabilities.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry);
            capabilities.setCapability(pair.getKey().toString(), pair.getValue().toString());

        Map<String, String> commonCapabilities = (Map<String, String>) config.get("capabilities");
        it = commonCapabilities.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry);
            if(capabilities.getCapability(pair.getKey().toString()) == null){
                capabilities.setCapability(pair.getKey().toString(), pair.getValue().toString());

        String username = System.getenv("BROWSERSTACK_USERNAME");
        if(username == null) {
            username = (String) config.get("user");

        String accessKey = System.getenv("BROWSERSTACK_ACCESS_KEY");
        if(accessKey == null) {
            accessKey = (String) config.get("key");

        if(capabilities.getCapability("browserstack.local") != null && capabilities.getCapability("browserstack.local") == "true"){
            l = new Local();
            Map<String, String> options = new HashMap<String, String>();
            options.put("key", accessKey);

        driver = new RemoteWebDriver(new URL("https://"+username+":"+accessKey+"@"+config.get("server")+"/wd/hub"), capabilities);

    public void tearDown() throws Exception {
        if(l != null) l.stop();

    public void runStories() throws Exception {
        Class<?> c = Class.forName(System.getProperty("embedder"));
        Constructor<?> cons = c.getConstructor(WebDriver.class);
        Embedder storyEmbedder = (Embedder) cons.newInstance(driver);

        List<String> storyPaths = Arrays.asList(System.getProperty("stories"));

We now need to create a config file, single.conf.json, which contains the BrowserStack Hub URL and credentials required to connect to the BrowserStack Selenium grid.

  "server": "",
  "user": "YOUR_USERNAME",
  "key": "YOUR_ACCESS_KEY",

  "capabilities": {
    "name": "Bstack-[JBehave] Sample Test",
    "browserstack.debug": true

  "environments": [{
    "browser": "chrome"

We are now ready to run the test on BrowserStack, using the following command:

# Run using maven
mvn test -P single

Mark tests as pass / fail

BrowserStack provides a comprehensive REST API to access and update information about your tests. Shown below is a sample code snippet which allows you to mark your tests as pass or fail based on the assertions in your JBehave test cases.

// Mark test as pass / fail

public static void mark() throws URISyntaxException, UnsupportedEncodingException, IOException {
    URI uri = new URI("<session-id>.json");
    HttpPut putRequest = new HttpPut(uri);

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add((new BasicNameValuePair("status", "completed")));
    nameValuePairs.add((new BasicNameValuePair("reason", "")));
    putRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));


A full reference of our REST API can be found here.

Debug your app

BrowserStack provides a range of debugging tools to help you quickly identify and fix bugs you discover through your automated tests.

  • Text Logs

Text Logs are a comprehensive record of your test. They are used to identify all the steps executed in the test and troubleshoot errors for the failed step. Text Logs are accessible from the Automate dashboard or via our REST API.

  • Visual Logs

Visual Logs automatically capture the screenshots generated at every Selenium command run through your JBehave tests. Visual logs help with debugging the exact step and the page where failure occurred. They also help identify any layout or design related issues with your web pages on different browsers.

Visual Logs are disabled by default. In order to enable Visual Logs you will need to set browserstack.debug capability to true.

"capabilities": {
  "browserstack.debug": true
  • Video recording

Every test run on the BrowserStack Selenium grid is recorded exactly as it is executed on our remote machine. This feature is particularly helpful whenever a browser test fails. You can access videos from Automate Dashboard for each session. You can also download the videos from the Dashboard or retrieve a link to download the video using our REST API.

Note: Video recording increases test execution time slightly. You can disable this feature by setting the capability to false.

To disable video recording, add the following code snippet:

"capabilities": {
  "": false

In addition to these logs BrowserStack also provides Raw logs, Network logs, Console logs, Selenium logs, Appium logs and Interactive session. Complete details to enable all the debugging options can be found here.