admin管理员组

文章数量:1391943

Normally, Cucumber tests run at the maven "test" phase of the build process. And all the needed data is kept in src/test - step-efinitions and feature files, etc. I need to be able to run them at application runtime - probably I'd want to trigger them with an endpoint. The Cucumber runner should be able to have access to the application context and all its components. I know this may not be what the makers of Cucumber had intended, but I want to know if it's possible, and if so, how?

Normally, Cucumber tests run at the maven "test" phase of the build process. And all the needed data is kept in src/test - step-efinitions and feature files, etc. I need to be able to run them at application runtime - probably I'd want to trigger them with an endpoint. The Cucumber runner should be able to have access to the application context and all its components. I know this may not be what the makers of Cucumber had intended, but I want to know if it's possible, and if so, how?

Share Improve this question asked Mar 14 at 7:15 Sougata GhoshSougata Ghosh 301 silver badge6 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Yes, it's possible to run Cucumber tests at runtime, triggered via an endpoint, while ensuring that the Cucumber runner has access to the Spring application context and all its components. Just make sure to define a cucumber runner that can be triggered

import io.cucumber.core.cli.Main;
import .springframework.stereotype.Service;

@Service
public class CucumberTestRunnerService {

    public void runTests() {
        String[] cucumberOptions = new String[]{
            "-g", "com.example.stepdefinitions", // Package where step definitions are located
            "src/test/resources/features",      // Path to feature files
            "--plugin", "pretty"
        };

        Main.run(cucumberOptions, Thread.currentThread().getContextClassLoader());
    }
}

Take note:

  1. Running tests at runtime like this may not be ideal for all scenarios (e.g., performance, security).

  2. Running tests asynchronously in a new thread (new Thread(() -> ...)) prevents blocking the request.

  3. Ensure step definitions and feature files are available in the runtime classpath.

本文标签: javaRunning Cucumber tests at runtimeStack Overflow