5 easy steps to integrate Cucumber Report with Karate and dynamic environment switching

Priyanka Brahmane
4 min readJul 12, 2022

Buenos dias TestCommunity!!!

Great to have you back.😀

After receiving numerous requests for today’s topic from my devoted audience, here it is: the much anticipated chapter on the Karate API Automation framework that focuses on reporting, with a bonus explanation of the logic used to dynamically provide the execution environment from the command line.

You must be as eager to begin the implementation as I am!! let’s get started.

Step 1: Add latest cucumber reporting maven dependency in pom.xml file.

Copy the dependency and paste it under <dependencies> tag as shown in below code snippet.

<dependency><groupId>net.masterthought</groupId><artifactId>cucumber-reporting</artifactId><version>5.7.2</version><scope>test</scope></dependency>

Step 2: Conditional environment switching logic.

Go to the karate-config.js file and set environment-specific variables like base-url, api-key, username, etc. (as required) that will change depending on your environment within the if-else section.

function fn() {if (!env) {env = 'staging';}var config = {
// variables & api paths
}//'karate.env' - Get system propertyvar env = karate.env; karate.log('karate.env system property was:', env);if (env == 'prod') {config.baseUrl = 'https://xyz.mgapis.com/';} else if (env == 'staging') {config.baseUrl = 'https://abc.net/';}karate.configure('connectTimeout', 5000);karate.configure('readTimeout', 5000);return config;}

Step 3: Integrate a logic in the Runner file to identify defined environment variable from a maven command.

The next line of code retrieves the environment variable from the command line and sets it internally in the var env = karate.env; of the karate-config.js file for use when the testcases are executed.

System.setProperty("karate.env",System.getProperty("karate.env"));

You can make ctrl + c (copy) and ctrl + v (paste) following code snippet in your project-

import com.intuit.karate.Results;
import com.intuit.karate.Runner;
import net.masterthought.cucumber.Configuration;
import net.masterthought.cucumber.ReportBuilder;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static junit.framework.TestCase.assertTrue;
public class TestRunner {@Test
public void testParallel() {
File file = new File("target/cucumber-html-reports/");
String[] myFiles;
if(file.isDirectory()){
myFiles = file.list();
for (int i=0; i<myFiles.length; i++) {
File myFile = new File(file, myFiles[i]);
System.out.println("Deleteing files: "+myFile);
myFile.delete();
}
}

String karateOutputPath = "target/surefire-reports/";
long starttime = System.nanoTime();
long endtime = System.nanoTime();
System.setProperty("karate.env",System.getProperty("karate.env"));
Results results = Runner.path("classpath:api/abc/test/")
.outputCucumberJson(true)
.parallel(1);
TestRunner.generateReport(results.getReportDir());
assertTrue(results.getErrorMessages(), results.getFailCount() == 0);
}

public static void generateReport(String karateOutputPath) {

Collection<File> jsonFiles = FileUtils.listFiles(new File(karateOutputPath), new String[] {"json"}, true);
List<String> jsonPaths = new ArrayList<String>(jsonFiles.size()); jsonFiles.forEach(file -> jsonPaths.add(file.getAbsolutePath())); Configuration config = new Configuration(new File("target"), "Report-Name"); ReportBuilder reportBuilder = new ReportBuilder(jsonPaths, config); reportBuilder.generateReports();
}
}

Above code in the Runner file will carry out the following activities:

  • Deletes all the previous report files.
  • Fetch “env” variable from maven command and execute all feature files in the specified environment.
  • Store all the relevant html reports in the “target/cucmber-html-reports” folder post current execution as shown below.

💡Pro-Tip💡: If your design uses microservices, ensure that the Runner file name is distinct for each microservice and update the blocked text accordingly.

Step 4: Maven command to pass the execution environment dynamically.

If you observe the command below, you will see -DargLine along with -Dkarate.env=ENV_NAME . Here, you may pass the environment name in which you want to execute all the scenarios.

mvn clean test -Dtest=TestRunner -DargLine="-Dkarate.env=ENV_NAME"

Refer the official documentation for more details.

Note - ENV_NAME is case-sensitive.

💡Tip💡- If you pass either staging or prod into karate.env, we can verify the same by checking execution logs —

Example 1: Execute for ‘prod(uction)’ environment

mvn clean test -Dtest=TestRunner -DargLine="-Dkarate.env=prod"

Example 2: Execute for ‘staging’ environment.

mvn clean test -Dtest=TestRunner -DargLine="-Dkarate.env=staging"

Step 5: Its time to view 👀 the Cucumber report.

Once the build has been completed successfully, refresh the project, navigate to the “target/cucumber-html-reports/” folder, and copy the link to the “overview-features.html” file.

Now paste the link into your web browser.

Voila!!! Here is your stunning cucumber report.

You may also integrate this report in your CICD pipeline to trigger an email or slack notification for the concerned people/team.

Now, Its time for me to conclude this blog here with the firm belief that it will help you create an aesthetically attractive yet concise Cucumber HTML report that can be shared and dramatically enhance API testing by alerting about the failures.

To express your interest for my blogs, don’t forget to hit the clap button below. Bookmark my Medium channel by clicking the follow button to receive notifications on new blog publish. Join my LinkedIn network and follow for more updates.

Hasta-la-vista 👋🏻 !!! Until then, stay safe and keep learning 🙂!!!

--

--

Priyanka Brahmane

AM SDET Automation @M&G | QA Lead @ MyGlamm | QA Automation engineer @ Ex-Paytm Insider| Ex-Automation Tester @ Reliance Jio Infocomm Ltd. | Ex-Software Develop