Search code examples
javaselenium-webdrivercucumbertestngcucumber-java

Cucumber and TestNG Parameters conflict


I am unable to set parameters through cucumber feature file as TestNG throws error because of the Parameter conflict

"Cannot inject @Test annotated Method [days_of_the_week_is_enabled_by_default] with [class java.lang.String, class java.lang.String]" 

As you see from the below code snippet, I am using cucumber's feature file to pass the parameter to the method but when I add the testNG annotation @Test, It throws me an error as cannot inject @Test.

I am aware how to use Parameters in TestNG but I want the Parameters to be taken from Feature file instead of TestNG Parameters. Anyway we could accomplish this ?

@Test
@Then("^(.*) is (.*) by default$")
public void days_of_the_week_is_enabled_by_default(String dOWeek, String status) {
        draftPage.daysSelectionDefault(dOWeek, status);
    }

Solution

  • That cannot be done. You can make use of TestNG as a runner to run your cucumber based tests. But that would perhaps lead to TestNG creating one @Test method which runs all the feature files. You can replace TestNG and use JUnit for the same too.

    You would need to employ other mechanisms such as JVM arguments perhaps to pass parameters to your cucumber tests.

    The other option would be for you to build a TestNG listener, and from it get hold of the ITestContext and through the test context, you can extract out the parameters.

    //This class is not thread safe, and will give unpredictable results
    //if you multiple <test> tags running.
    import org.testng.ITestContext;
    import org.testng.ITestListener;
    
    public class LocalListener implements ITestListener {
    
      private static LocalListener instance;
      private ITestContext testContext;
    
      private static void setInstance(LocalListener obj) {
        instance = obj;
      }
    
      public static LocalListener getInstance() {
        return instance;
      }
    
      public LocalListener() {
        setInstance(this);
      }
    
      @Override
      public void onStart(ITestContext context) {
        this.testContext = context;
      }
    
      public ITestContext getTestContext() {
        return testContext;
      }
    }