Home Guide How to integrate Jira with Selenium

How to integrate Jira with Selenium

By Ganesh Hegde, Community Contributor -

Table of Contents

Selenium is the most popular automation testing framework in the world. Selenium Webdriver is used for automation testing by testers across teams and organizations, and for good reason. 

Among its many advantages, one of Selenium’s unique features is its extensibility. That means testers can create their own frameworks as required, extend them and hook them up with multiple services. Because of its unique feature, Selenium stands out from all available modern frameworks.

Given that Jira is one of the most popular issue tracking and project management tools used by Agile development and testing teams, it is common for testers to integrate Selenium with Jira for greater efficiency and more accurate results.

This article discusses how to integrate Selenium with Jira in a minimum-hassle way. 

What is Jira?

Jira is a tool primarily used for bug and issue tracking. It also supports project management features for all kinds of use cases, from requirements and test case management to Agile software development. 

Jira is free to use for up to 20 users. However, if any organization requires additional features like support, storage, and a large user limit they must go for the commercial version. Since Jira is a bug/issue tracking tool, it enables the assignment, resolution, and implementation of bug life cycle management. 

Jira also provides Rest API endpoints with which testers can automate multiple actions such as Create Issue, Assign Issue, Search the Issue, etc. So, if QAs are utilizing Selenium test automation they can directly log an issue in Jira using Jira API endpoints without the need for manual interventions. 

The following sections will describe how to create API Tokens, how to use Jira API, and how to create issues with Selenium.

How to Create API Token in Jira

Jira API tokens allow a user to authenticate with cloud apps and bypass two-step verification and SSO in order to retrieve data from the instance through REST APIs. Token controls allow admins to view and revoke the use of API tokens by their managed accounts.

Basically, using the access token and user name, testers can connect Selenium and Jira.

Steps to generate API token in Jira

  1. Navigate to your Organization Jira website (ex: https://example.atlassian.net/)
  2. Login with credentials
  3. Click on Profile and Settings
  4. Click on Account SettingsJIRA Selenium Example
  5.  Click on Security. Then, click on Create and manage API tokensJIRA security
  6. In the API Tokens section Click on Create API token
    Create API Tokens for JIRA
  7. Enter the Label and click on Create
    JIRA Token Demo
  8. Once the token is created, copy and save it in the desired location.

Note: After creating the API token don’t forget to copy and save the token in the text editor. The token is not accessible once the pop-up disappears.

By following these step-by-step guidelines, users can create an API Token in Jira, which can be used to call Jira REST API endpoints inside someone’s Selenium Jira integration sections.

How to connect Selenium with Jira and log defects in Jira using Selenium

Let’s start with the prerequisites

  1. The Eclipse IDE, already installed.
  2. The basic Maven Project Set up, already in place.

Note: This example uses TestNG, Selenium, the Maven Automation Framework, and Java as programming languages.

Now, let’s explore how to integrate Jira with Selenium and then log defects in Jira.

  • Problem Statement: The user has their Selenium tests. When they execute the tests, and any of them fail, a Jira ticket should be automatically created under the relevant Project. 
  • Condition: If the same ticket has already been created in that particular project, ticket creation should be skipped.

Note: Without this condition, projects end up with a lot of duplicate issues each time they re-run multiple tests.

Step 1: Add required dependencies in pom.xml

In order to Integrate Jira with Selenium, use rcarz Jira-client for simplicity. This is the wrapper built on top of the Jira Rest API Client.

Navigate to pom.xml in the project, and add the following dependency:

<dependency>

      <groupId>net.rcarz</groupId>

      <artifactId>Jira-client</artifactId>

      <version>0.5</version>

      <scope>compile</scope>

 </dependency>


Step 2: Create basic tests using Selenium and Java

Let’s create some basic tests. This example creates two basic tests: one should pass and one should fail.

These tests are created under the package com.demo.project (placed in a desirable location)

Selenium JIRA steps

Source Code: HomePageTest.java

 

// HomePageTest.java

package com.demo.project;

import static org.testng.Assert.assertEquals;

import static org.testng.Assert.assertTrue;

import java.io.File;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.AfterClass;

import org.testng.annotations.BeforeClass;

import org.testng.annotations.Test;

import com.demo.utility.JiraCreateIssue;

public class HomePageTest {

    private WebDriver driver;

    private String baseUrl;




    @BeforeClass(alwaysRun = true)

    public void setUp() throws Exception {

        File chromedriverExecutable = new File("driver/chromedriver.exe");

        System.setProperty("webdriver.chrome.driver"chromedriverExecutable.getAbsolutePath());

        driver = new ChromeDriver();

        baseUrl = "https://www.browserstack.com/";

        driver.manage().timeouts().implicitlyWait(30TimeUnit.SECONDS);

    }


//Custom annotation explained in following sections

    @JiraCreateIssue(isCreateIssue=true

    @Test

    public void verifyHomepageHeaderText() throws Exception {

        driver.get(baseUrl);

        WebElement el = driver.findElement(By.xpath("//h1[1]"));

        assertEquals(el.getText(), "Browser Testing Made Easy","Wrong header text displayed in Home page");

    }
    

    @JiraCreateIssue(isCreateIssue=true)

    @Test

    public void verifyHomePageLogo() throws Exception {

        driver.get(baseUrl);

        WebElement el = driver.findElement(By.id("logo"));

        assertTrue(el.isDisplayed(),"The browserstack logo not displaying in home page");

    }


    @AfterClass(alwaysRun = true)

    public void tearDown() throws Exception {

        driver.quit();

    }

}


Sample Screenshot
Sample Screenshot

Step 3: Create a utility to handle Jira issue

Let’s create a package inside the main folder com.demo.utility, which will contain two classes

  1. JiraServiceProvider: This class will have a method to create a Jira issue.
  2. JiraCreateIssue: This contains custom annotation code.

Below is the folder structure
Sample Folder Structure

Note: Custom annotation is optional but this provides flexibility to pick and choose tests to be made eligible for ticket creation. For example, if some tests are not production-ready there’s no need to create tickets for them.

Source Code: JiraServiceProvider.java

// JiraServiceProvider.java

package com.demo.utility;

import net.rcarz.Jiraclient.BasicCredentials;

import net.rcarz.Jiraclient.Field;

import net.rcarz.Jiraclient.Issue;

import net.rcarz.Jiraclient.Issue.FluentCreate;

import net.rcarz.Jiraclient.JiraClient;

import net.rcarz.Jiraclient.JiraException;


public class JiraServiceProvider {


     private JiraClient Jira;

     private String project;

     private String JiraUrl;

     public JiraServiceProvider(String JiraUrlString usernameString passwordString project) {

         this.JiraUrl=JiraUrl;

         // create basic authentication object

         BasicCredentials creds = new BasicCredentials(username, password);

         // initialize the Jira client with the url and the credentials

         Jira = new JiraClient(JiraUrl, creds);

         this.project = project;

     }


    public void createJiraIssue(String issueTypeString summaryString descriptionString reporterName) {




        try {

            //Avoid Creating Duplicate Issue

            Issue.SearchResult sr = Jira.searchIssues("summary ~ \""+summary+"\"");

            if(sr.total!=0) {

                System.out.println("Same Issue Already Exists on Jira");

                return;

            }

            

            //Create issue if not exists

            FluentCreate fleuntCreate = Jira.createIssue(project, issueType);

            fleuntCreate.field(Field.SUMMARY, summary);

            fleuntCreate.field(Field.DESCRIPTION, description);

            Issue newIssue = fleuntCreate.execute();

            System.out.println("********************************************");

            System.out.println("New issue created in Jira with ID: " + newIssue);

            System.out.println("New issue URL is :"+JiraUrl+"/browse/"+newIssue);

            System.out.println("*******************************************");

        } catch (JiraException e) {

            e.printStackTrace();

        }

    }

}

JiraCreateIssue.java : This is for Custom Annotation to be used inside Selenium tests.

Source Code: JiraCreateIssue.java

// JiraCreateIssue.java

package com.demo.utility;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Retention;

@Retention(RetentionPolicy.RUNTIME)

public @interface JiraCreateIssue {

    boolean isCreateIssue();

}


Step 4: Create Listener to notify test failures

Create a listener so that each time a test fails, it should automatically create the Jira issue method. This listener keeps track of test failures and executes specified code.

This example names the listener as TestListener.java, created inside package com.demo.listener.

Source Code: TestListener.java

//TestListener.java

package com.demo.listener;

import org.apache.commons.lang.exception.ExceptionUtils;

import org.testng.ITestContext;

import org.testng.ITestListener;

import org.testng.ITestResult;

import com.demo.utility.JiraCreateIssue;

import com.demo.utility.JiraServiceProvider;


public class TestListener implements ITestListener {


    @Override

    public void onTestFailure(ITestResult result) {

        boolean islogIssue = result.getMethod().getConstructorOrMethod().getMethod().getAnnotation(JiraCreateIssue.class).isCreateIssue();

        if (islogIssue) {

//Provide proper Jira project URL ex: https://browsertack.atlassian.net 

//Jira User name ex: browserstack@gmail.com

//API token copy from Jira dashboard ex: lorelimpusm12uijk

//Project key should be, Short name ex: BS


            JiraServiceProvider JiraServiceProvider = new JiraServiceProvider("https://example.atlassian.net",

                    "example@gmail.com""lorelimpusm12uijk""BS");



            String issueDescription = "Failure Reason from Automation Testing\n\n" + result.getThrowable().getMessage()

                    + "\n";

            issueDescription.concat(ExceptionUtils.getFullStackTrace(result.getThrowable()));




            String issueSummary = result.getMethod().getConstructorOrMethod().getMethod().getName()

                    + " Failed in Automation Testing";

            

            JiraServiceProvider.createJiraIssue("Bug", issueSummary, issueDescription, "Automated Testing");

        }

    }

    @Override

    public void onTestSkipped(ITestResult result) {

        // TODO Auto-generated method stub




    }

    @Override

    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {

        // TODO Auto-generated method stub


    }

    @Override

    public void onStart(ITestContext context) {

        // TODO Auto-generated method stub


    }


    @Override

    public void onFinish(ITestContext context) {

        // TODO Auto-generated method stub


    }


    @Override

    public void onTestStart(ITestResult result) {

        // TODO Auto-generated method stub


    }


    @Override

    public void onTestSuccess(ITestResult result) {

        // TODO Auto-generated method stub


    }

}


Important Points to remember when creating a JiraServiceProvider object:

  • JiraUrl: This should be a company Jira URL. If someone is using the Jira cloud it will be something like: https://xyz.atlassian.net 
  • username: This parameter is the login name (typically email) but depends on the configuration (ex: xyz@gmail.com)
  • password: If using the Jira cloud, one must pass the API Token as a password. Using one’s login password might not work (example API token: lorelimpusm12uijk)
  • project: This is the project Key, often named with two letters (ex: BS). Using the full project name like BrowserStack Project might not work, so always use the short version. 

How to get project key In Jira

  1. Navigate to Jira URL (https://example.atlassian.net)
  2. Click on Projects Menu 
  3. Click on View All Projects
  4. Choose the Desired Project 
  5. On Project Page, Click on Project Settings
  6. Look for the field Key. This is the short project Key
  7. Just copy and use it as a project key

After completion of Step 4 the project looks as below:
Step 4 of Selenium JIRA setup

Step 5: Configure the testng.xml file

Once we have all the required set up, we need to have a testng.xml file configured to run our tests. Our sample xml file looks like below. (You can use your existing testng.xml file to run your tests).

Source Code: Sample testng.xml file

<?xml version="1.0" encoding="UTF-8"?>

<suite name="Default suite" parallel="methods" verbose="3">

     <listeners>

        <listener class-name="com.demo.listener.TestListener" />

    </listeners>

     <test name=" First test" skipfailedinvocationcounts="false">

         <classes>

             <class name="com.demo.project.HomePageTest">             

             </class>

         </classes>

     </test>

</suite>


Step 6: Execute your tests

Once setup is complete, execute the tests. Once tests are executed, any failures should automatically create a Jira ticket. After execution, view the result in the console.

Sample Console Output

If everything is correct then after all Selenium tests run, it will create a Jira Issue, and the console will return as output – Ticket ID/Issue ID (ex: 32 in above image). It will also offer the URL to navigate to that particular issue.

Step 7: Ensure ticket created in Jira

Let’s navigate to the Jira dashboard to check whether an issue has been created or not. In the Jira dashboard, click on the project dashboard to see if a new issue has been created, as shown below:

Most of the operations performed through the Jira user interface can be run using the REST API client. The Jira REST API client allows testers to automate the issue tracking and logging process, reducing the need for manual effort and attention. 

Bear in mind Selenium WebDriver tests must be executed on real devices and browsers. Remember that device fragmentation is a major concern for every developer and tester. Every website has to work seamlessly on multiple device-browser-OS combinations. With 9000+ distinct devices being used to access the internet globally, all software has to be optimized for different configurations, viewports, and screen resolutions.

In this state, no emulator or simulator can replicate real user conditions. Software needs to be tested on real devices so that they can work in real-world circumstances such as a low battery, incoming calls, weak network strength, and so on. If an in-house lab is not accessible, opt for a cloud-based testing option that offers real devices.

BrowserStack’s cloud Selenium grid offers 2000+ real devices and browsers for automated testing. That means users can run tests on multiple real devices and browsers by simply signing up, logging in, and selecting the required combinations. Testers can also conduct Cypress testing on 30+ real browser versions across Windows and macOS. Detects bugs before users do by testing software in real user conditions with BrowserStack.

Run Selenium Tests on Real Browsers & Devices

Tags
Automation Testing Selenium Selenium Webdriver

Featured Articles

getAttribute() method in Selenium: What, Why, and How to use

5 Selenium tricks to make your life easier

A Guide to Enterprise Test Automation: Why It Matters

BrowserStack Logo Run Selenium Tests on 2000+ Browsers & Devices Contact us Get Started Free