You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Karate框架中针对特定feature文件遍历Excel行及Java调用?

Hey there! I’ve worked with Karate and Excel-driven testing quite a bit, so let’s walk through how to solve your questions clearly.

整体思路

Since you already have an ExcelUtility class, the core approach is straightforward:

  1. Use your utility to read all rows from your Excel sheet into a list of key-value maps (each map represents one row, with column names as keys).
  2. Loop through each row in Java, and use Karate's Runner API to execute your target feature file, passing the current row's data to the feature for each run.

Step 1: Ensure Your ExcelUtility Returns Structured Data

First, make sure your ExcelUtility.readExcel() method returns a List<Map<String, Object>>. For example, if your Excel has columns username, password, expectedStatus, each map in the list should look like this:

{
  "username": "testuser1",
  "password": "pass123",
  "expectedStatus": 200
}

This structure makes it easy to pass and reference data in your Karate feature.


Step 2: Java Code to Loop Through Excel Rows & Call Karate Feature

Create a JUnit (or TestNG) test class that uses Karate's Runner to execute your feature for each Excel row. Here's a complete, working example:

import com.intuit.karate.Runner;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import your.package.name.ExcelUtility; // Replace with your actual package path

public class ExcelDrivenKarateTest {

    @Test
    public void runFeatureWithExcelData() {
        // 1. Read all test data rows from Excel
        List<Map<String, Object>> testData = ExcelUtility.readExcel("src/test/resources/test-data.xlsx", "LoginTests");

        // 2. Iterate over each row to run the feature
        for (int i = 0; i < testData.size(); i++) {
            Map<String, Object> rowData = testData.get(i);
            System.out.println("Executing test case " + (i+1) + " with data: " + rowData);

            try {
                // 3. Execute the target feature with current row data
                Runner.path("classpath:features/login.feature")
                      // Pass row data to Karate's config (accessible via #(excelRowData.key))
                      .configProperty("excelRowData", rowData)
                      // Optional: Filter features by tags (skip ones marked @skip)
                      .tags("~@skip")
                      // Run in sequence (parallel=1) since we're looping row by row
                      .parallel(1);
            } catch (Exception e) {
                // Handle failures without stopping the entire test suite
                System.err.println("Test case " + (i+1) + " failed: " + e.getMessage());
            }
        }
    }
}

Step 3: Use Excel Data in Your Karate Feature

In your target feature file (e.g., login.feature), reference the passed data using Karate's expression syntax #(excelRowData.<column-name>):

Feature: Login API Tests with Excel-Driven Data

Scenario: Validate user login
    Given url 'https://your-api-domain.com/auth/login'
    And request {
        username: '#(excelRowData.username)',
        password: '#(excelRowData.password)'
    }
    When method POST
    Then status #(excelRowData.expectedStatus)
    And match response.message contains 'Login successful'

Key Tips & Notes

  • Reporting: By default, Karate merges all test reports. If you want separate reports for each Excel row, add .reportDir("target/karate-reports/test-case-" + (i+1)) to the Runner configuration.
  • Parallel Execution: We set parallel(1) here because we're already looping in Java. If you want true parallelism, you could convert Excel data to JSON/CSV and use Karate's built-in data-driven features, but the Java loop approach is simpler for your existing setup.
  • Data Cleanup: Add checks in your ExcelUtility to skip empty rows or header rows if your Excel sheet includes them.

内容的提问来源于stack exchange,提问作者Velu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:14:15