Search code examples
cucumbercucumber-javacucumber-junit

Cucumber : Retrieve the name of the runner or his class name


i have the below two runners :

@CucumberOptions(plugin = {"pretty", "json:target/cucumber_parallel_BR00.json", "junit:target/cucumber_parallel-junit-report-BR00.xml",
        "rerun:target/failed_scenarios/failed_parallel_once_BR00.txt", "timeline:target/timeline_BR00"},
        features = {"classpath:features/parallel/BR00"},
        tags = "(@UI or @API) and (not @Ignored)",
        glue = {"com.intrasoft.ermis.e2e.stepdefs"},
        monochrome = true)

public class E2ECucumberParallelRunner_BR00 extends AbstractTestNGCucumberTests {

and

@CucumberOptions(plugin = {"pretty", "json:target/cucumber_parallel_BR01.json", "junit:target/cucumber_parallel-junit-report-BR01.xml",
        "rerun:target/failed_scenarios/failed_parallel_once_BR01.txt", "timeline:target/timeline_BR01"},
        features = {"classpath:features/parallel/BR01"},
        tags = "(@UI or @API) and (not @Ignored)",
        glue = {"com.intrasoft.ermis.e2e.stepdefs"},
        monochrome = true)

public class E2ECucumberParallelRunner_BR01 extends AbstractTestNGCucumberTests {

during the execution of @BeforeAll i would like to retrieve the name of the runner or the name of the class because based on the runner i would like to set same data in the env before all scenarios


Solution

  • You can approach with two steps:

    1. Create a static holder of current runner identifier like
    public class RunnerInfo {
    
      private static name;
    
      public static setName(String value){
        if(name == null){
          name = value;
        }else{
          throw new IllegalStateException("Runner name has been alread identified");
        }
      }
    
      public static String getName(){
        return name;
      }
    
    }
    
    1. Since you are using TestNg as test runner you can simply add constructor to your runner that would set up any name you want.
    public class Runner1 extends AbstractTestNGCucumberTests {
    
      public Runner1(){
        RunnerInfo.setName("My runner");
      }
    
    } 
    

    and for another one

    public class Runner2 extends AbstractTestNGCucumberTests {
    
      public Runner2(){
        RunnerInfo.setName("My another runner");
      }
    
    } 
    

    Now let's retrieve the name from the hook:

    public class MyHook {
    
      @BeforeAll
      public static void globalSetUp(){
        System.out.println(RunnerInfo.getName());
      }
    
    }