Hot questions for Using Cucumber in exception

Question:

I'm getting an odd error when I try to run verify lifecycle of maven for my java spring project. Note that it compiles fine using mvn spring-boot:run but when I run mvn clean verify it blows up with:

$mvn clean verify -Dsurefire.skip=true -X
...
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.209 sec <<< FAILURE! - in com.fitforger.FitForgerBackendApplicationTests
    initializationError(com.fitforger.FitForgerBackendApplicationTests)  Time elapsed: 0.005 sec  <<< ERROR!
    java.lang.NoClassDefFoundError: com/fitforger/model/GymRat
    Caused by: java.lang.ClassNotFoundException: com.fitforger.model.GymRat

What can I provide to be relevant? See below for some initial context.

Project structure:

+----src
     +----main
     |    +----java
     |    |    +----com
     |    |         +----fitforger
     |    |              +----controller
     |    |              |    +----GymRatController.java
     |    |              |    +----WorkoutNodeController.java
     |    |              +----dao
     |    |              |    +----GymRatDAO.java
     |    |              +----exception
     |    |              |    +----GymRatCreationFailure.java
     |    |              |    +----GymRatExistsException.java
     |    |              |    +----GymRatNotFound.java
     |    |              |    +----GymRatUpdateFailure.java
     |    |              +----FitForgerBackendApplication.java
     |    |              +----model
     |    |              |    +----FitForgerModel.java
     |    |              |    +----GymRat.java
     |    |              |    +----WorkoutAttribute.java
     |    |              |    +----WorkoutNode.java
     |    |              |    +----WorkoutNodeTypes.java
     |    |              +----repository
     |    |                   +----CouchbaseRepository.java
     |    |                   +----FitForgerRepository.java
     |    +----resources
     |         +----application.properties
     +----test
          +----java
          |    +----com
          |         +----fitforger
          |              +----FitForgerBackendApplicationTests.java
          |              +----GymRatSteps.java
          |              +----repository
          |                   +----CouchbaseRepositoryTest.java
          +----resources
               +----com
                    +----fitforger
                         +----GymRat.feature

Relevant bits of my pom.xml:

<build>
    <resources>
        <resource>
            <directory>resources</directory>
            <targetPath>${project.build.outputDirectory}</targetPath>
            <includes>
                <include>application.properties</include>
            </includes>
        </resource>
    </resources>

    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.19.1</version>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.5.1.RELEASE</version>
        </plugin>
    </plugins>

    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.5.1.RELEASE</version>
                <executions>
                    <execution>
                        <id>pre-integration-test</id>
                        <goals>
                            <goal>start</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>post-integration-test</id>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <excludes>
                        <exclude>com.fitforger.FitForgerBackendApplicationTests</exclude>
                    </excludes>
                    <skip>${surefire.skip}</skip>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <includes>
                        <include>com.fitforger.FitForgerBackendApplicationTests</include>
                    </includes>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </pluginManagement>
</build

Answer:

OP problem solved by doing below,

This looks to be similar to what you are facing. Could you try with

<plugin>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-maven-plugin</artifactId>
   <configuration>
        <classifier>exec</classifier>
   </configuration>
 </plugin>

Question:

I am facing an error whenever I run the cucumber test by Junit. Here is the following Exception. Any help will be awesome

NOTE:

THERE IS NO ERROR IN THE PROJECT

java.lang.NoClassDefFoundError: cucumber/io/ResourceLoader
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2398)
    at java.lang.Class.getConstructor0(Class.java:2708)
    at java.lang.Class.getConstructor(Class.java:1659)
    at cucumber.runtime.Reflections.hasConstructor(Reflections.java:53)
    at cucumber.runtime.Reflections.instantiateSubclasses(Reflections.java:29)
    at cucumber.runtime.Runtime.loadBackends(Runtime.java:96)
    at cucumber.runtime.Runtime.<init>(Runtime.java:63)
    at cucumber.api.junit.Cucumber.createRuntime(Cucumber.java:74)
    at cucumber.api.junit.Cucumber.<init>(Cucumber.java:61)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:29)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:21)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException: cucumber.io.ResourceLoader
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 28 more

Here is how my POM.xml looks like:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Test</groupId>
  <artifactId>Cucumber</artifactId>
  <version>0.0.1-SNAPSHOT</version>
<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

           <!-- Cucumber -->   
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.1.8</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
            <version>2.42.2</version>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.0.0.RC5</version>
            <scope>test</scope>
        </dependency>
</dependencies>
</project>

Here is the image of my project structure:

And here is my RunIT.Java Class

package com.Cucumber;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;


@RunWith(Cucumber.class)
@CucumberOptions(
        tags={"@mysingle"},
        features = {"."})
public class RunIT {

}

Answer:

It looks like you're missing the cucumber-core library.

Try adding the following to your dependencies.

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-core</artifactId>
        <version>1.1.8</version>
    </dependency>

Also, you appear to be mixing and matching versions. Try using the same version for all the cucumber-* libraries.

Question:

I'm getting an AmbiguousStepDefinitionsException with the following case, I don't understand how to solve this problem. Please help!

scenario

  Scenario Outline: Testing the price ordering filter
    When the <priceOrder> filter is clicked
    Then prices are ordered by <priceOrder>
    Examples:
    |  priceOrder |
    |  ascending  |
    |  descending |

  Scenario Outline: Testing the stars hotel filter
    When the <star> stars hotel filter is clicked
    Then all hotels are <star> stars
    Examples:
    |  star  |
    |    1   |
    |    2   |
    |    3   |
    |    4   |
    |    5   |

step file

    @When("^the (.*?) filter is clicked$")
    public void thePriceOrderFilterIsClicked(String priceOrder) {
        hotelPage.activatePriceFilter(priceOrder);
    }

    @When("^the (\\d+) stars hotel filter is clicked$")
    public void theStarStarsHotelFilterIsClicked(int star) {
        hotelPage.activateStarsFilter(String.valueOf(star));
    }

    @Then("^all hotels are (\\d+) stars$")
    public void allHotelsAreStarStars(int star) throws InterruptedException {
        hotelPage.checkHotelStars(String.valueOf(star));
    }

error

cucumber.runtime.AmbiguousStepDefinitionsException: ✽.When the 5 stars hotel filter is clicked(hotelSearches.feature:16) matches more than one step definition:
  ^the (.*?) filter is clicked$ in HotelSearchesSteps.thePriceOrderFilterIsClicked(String)
  ^the (\d+) stars hotel filter is clicked$ in HotelSearchesSteps.theStarStarsHotelFilterIsClicked(int)

Any idea? Thanks!


Answer:

The pattern that you use This pattern ^the (.*?) filter is clicked$ matching until the first occurrence of filter which will match both scenario's.

If you want the first scenario matched the <priceOrder> filter is clicked and the <priceOrder> can be for example ascending or descending, you could match 1+ word characters (\w+), only lowercase chars ([a-z]+) or use an alternation (ascending|descending) to make it specific.

For example keeping the capturing group:

the (\w+) filter is clicked

Question:

I seem to be getting a pico container exception: org.picocontainer.injectors.AbstractInjector$UnsatisfiableDependenciesException.

My code is as follows:

Page Object representing a specific page of a website:

     public class GooglePage {
        private WebDriver driver;

        private String stringLocator = "edffsfds";

        @FindBy(how = How.XPATH,using = "//div[@id='header']/ul[1]/li[11]/a")
        public WebElement logout;

          public GooglePage(WebDriver driver) {
              this.driver = driver;
              PageFactory.initElements(driver, this);
          }

        public WebElement getLogout() {
            return logout;
        }

        public void setLogout(WebElement logout) {
            this.logout = logout;
        }

        public String getExampleStringLocator() {
            return stringLocator;
        }
    }

Steps class:

    import CucumberNewExcel.transformer.pageObjects.GooglePage;
    import cucumber.api.java.en.Given;
    import cucumber.api.java.en.When;

    public class GoogleSteps {
        private GooglePage googlePage;

        public GoogleSteps(GooglePage googlePage) {
            this.googlePage = googlePage;
        }   

        @Given("^I access \"([^\"]*)\"$")
        public void i_access(String arg1) throws Throwable {
            //System.out.println("Hello: " + googlePage.getExampleStringLocator());
        }

        @When("^I click on the signin button$")
        public void i_click_on_the_signin_button() throws Throwable {
            //System.out.println("Hello: " + googlePage.getExampleStringLocator());
        }
    }

POM Dependencies:

<dependencies>
            <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-java</artifactId>
                <version>3.11.0</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-java</artifactId>
                <version>1.2.5</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-jvm</artifactId>
                <version>1.2.5</version>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-junit</artifactId>
                <version>1.2.5</version>
                <scope>test</scope>
            </dependency>


            <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-core -->
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-core</artifactId>
                <version>1.2.5</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-html -->
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-html</artifactId>
                <version>0.2.3</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-java</artifactId>
                <version>1.2.5</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-jvm-deps -->
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-jvm-deps</artifactId>
                <version>1.0.5</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/info.cukes/gherkin -->
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>gherkin</artifactId>
                <version>2.12.2</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest-all -->
            <dependency>
                <groupId>org.hamcrest</groupId>
                <artifactId>hamcrest-all</artifactId>
                <version>1.3</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-picocontainer</artifactId>
                <version>1.2.5</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-testng -->
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-testng</artifactId>
                <version>1.2.5</version>
            </dependency>

            <!-- Extent Reports -->
            <dependency>
                <groupId>com.aventstack</groupId>
                <artifactId>extentreports</artifactId>
                <version>3.0.5</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
            <dependency>
                <groupId>org.freemarker</groupId>
                <artifactId>freemarker</artifactId>
                <version>2.3.26-incubating</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/net.masterthought/cucumber-reporting -->
            <dependency>
                <groupId>net.masterthought</groupId>
                <artifactId>cucumber-reporting</artifactId>
                <version>3.6.0</version>
            </dependency>
            <dependency>
                <groupId>com.vimalselvam</groupId>
                <artifactId>cucumber-extentsreport</artifactId>
                <version>2.0.4</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/info.cukes/cucumber-jvm-deps -->
            <dependency>
                <groupId>info.cukes</groupId>
                <artifactId>cucumber-jvm-deps</artifactId>
                <version>1.0.5</version>
            </dependency>
        </dependencies>

For some reason when executing my feature file, I seem to be receiving the following exception any ideas?

org.picocontainer.injectors.AbstractInjector$UnsatisfiableDependenciesException: CucumberNewExcel.transformer.pageObjects.GooglePage has unsatisfied dependency 'interface org.openqa.selenium.WebDriver' for constructor 'public CucumberNewExcel.transformer.pageObjects.GooglePage(org.openqa.selenium.WebDriver)' from org.picocontainer.DefaultPicoContainer@2f67a4d3:2<|
    at org.picocontainer.injectors.ConstructorInjector.getGreediestSatisfiableConstructor(ConstructorInjector.java:191)
    at org.picocontainer.injectors.ConstructorInjector.getGreediestSatisfiableConstructor(ConstructorInjector.java:110)
    at org.picocontainer.injectors.ConstructorInjector.access$100(ConstructorInjector.java:51)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:331)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:632)
    at org.picocontainer.parameters.BasicComponentParameter$1.resolveInstance(BasicComponentParameter.java:118)
    at org.picocontainer.parameters.ComponentParameter$1.resolveInstance(ComponentParameter.java:136)
    at org.picocontainer.injectors.SingleMemberInjector.getParameter(SingleMemberInjector.java:78)
    at org.picocontainer.injectors.ConstructorInjector$CtorAndAdapters.getParameterArguments(ConstructorInjector.java:309)
    at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:335)
    at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
    at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
    at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
    at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
    at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
    at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
    at cucumber.runtime.java.picocontainer.PicoFactory.getInstance(PicoFactory.java:37)
    at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
    at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
    at cucumber.runtime.Runtime.runStep(Runtime.java:300)
    at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
    at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
    at cucumber.runtime.junit.ExecutionUnitRunner.run(ExecutionUnitRunner.java:102)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:63)
    at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:18)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:70)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:95)
    at cucumber.api.junit.Cucumber.runChild(Cucumber.java:38)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at cucumber.api.junit.Cucumber.run(Cucumber.java:100)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
    at ✽.Given I access "wwww.google.com"(google.feature:4)

Answer:

This happening because you are trying to create constructors in stepdefination file without putting picocontainer dependency. Its an dependency injection framework for cucumber

Either remove the constructor or add below dependency in POM

<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-picocontainer -->
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-picocontainer</artifactId>
    <version>1.2.5</version>
    <scope>test</scope>
</dependency>

You can remove <scope>test</scope> tag if do not want to limit the transitivity of a dependency

Question:

I've integrated Alluer to my cucumber automation project. After the integration, I can run the tests from feature files, and generate the report successfully as well. However, when I try to run the test from test entry class, there was an Exception came out. Can someone help me with this? Thank you very much.

Error message:

cucumber.runtime.CucumberException: Couldn't load plugin class: io.qameta.allure.cucumberjvm.AllureCucumberJvm

    at cucumber.runtime.formatter.PluginFactory.loadClass(PluginFactory.java:175)
    at cucumber.runtime.formatter.PluginFactory.pluginClass(PluginFactory.java:165)
    at cucumber.runtime.formatter.PluginFactory.getPluginClass(PluginFactory.java:226)
    at cucumber.runtime.formatter.PluginFactory.isFormatterName(PluginFactory.java:195)
    at cucumber.runtime.RuntimeOptions$ParsedPluginData.addPluginName(RuntimeOptions.java:365)
    at cucumber.runtime.RuntimeOptions.parse(RuntimeOptions.java:125)
    at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:89)
    at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:78)
    at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:70)
    at cucumber.runtime.RuntimeOptionsFactory.create(RuntimeOptionsFactory.java:25)
    at cucumber.api.junit.Cucumber.<init>(Cucumber.java:56)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.ClassNotFoundException: io.qameta.allure.cucumberjvm.AllureCucumberJvm
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at cucumber.runtime.formatter.PluginFactory.loadClass(PluginFactory.java:173)

Entry class:

@RunWith(Cucumber.class)
@CucumberOptions(
        features = {"src/test/resources/features"},
        glue = {"classpath:com.wi***rd.step"},
        format = {"pretty", "html:target/cucumber-report", "json:target/cucumber.json"},
        tags = {"@Mer***tion, @Add***nal, @MER***CH, @MER***ERR"}
)
public class A***dApplicationTests {
}

POM.xml

        <dependency>
            <groupId>ru.yandex.qatools.allure</groupId>
            <artifactId>allure-cucumber-jvm-adaptor</artifactId>
            <version>1.6.3</version>
        </dependency>
        <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-java-commons</artifactId>
            <version>2.0-BETA15</version>
        </dependency>        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20</version>
                <configuration>
                    <argLine>
                        -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                        -Dcucumber.options="--plugin io.qameta.allure.cucumberjvm.AllureCucumberJvm"
                    </argLine>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjweaver</artifactId>
                        <version>1.8.10</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>

    </build>

Answer:

The problem is that you are using old allure-cucumber-jvm-adaptor dependency. The correct one is

<dependency>
    <groupId>io.qameta.allure</groupId>
    <artifactId>allure-cucumber-jvm</artifactId>
    <version>2.0-BETA16</version>
</dependency>

Also there is no need to specify additional allure-java-commons dependency

Question:

I am getting following error while running my Cucumber Selenium tests using Spring Boot

I have already added Background in the feature file. Not sure how to generalize the parameters that are getting passed in it.

Please guide.

Error:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.example.TestRunner
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.388 sec <<< FAILURE! - in com.example.TestRunner
initializationError(com.example.TestRunner)  Time elapsed: 0.004 sec  <<< ERROR!
cucumber.runtime.DuplicateStepDefinitionException: Duplicate step definitions in com.example.stepdefs.GoogleCalcStepDefinition.I_enter_in_search_textbox(String) in file:/I:/pet-projects/junit-cucumber-demo/target/test-classes/ and com.example.stepdefs.GoogleCalcSte
pDefinition.I_enter_in_search_textbox2(String) in file:/I:/pet-projects/junit-cucumber-demo/target/test-classes/


Results :

Tests in error:
  TestRunner.initializationError » DuplicateStepDefinition Duplicate step defini...

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0

[ERROR] There are test failures.
[INFO] About to generate Cucumber report.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.281 s
[INFO] Finished at: 2019-04-12T16:50:23-04:00
[INFO] ------------------------------------------------------------------------

calc.feature

Feature: Check addition in Google calculatorcontent
  In order to verify that Google calculator work correctly
  As a user of Google
  I should be able to get correct addition result

  Background: Do some arithmetic on Google
    Given I open Google

  Scenario: Addition
    When I enter "2+2" in search textbox
    Then I should get result as "4"

  Scenario: Multiplication
    When I enter "5*5" in search textbox
    Then I should get result as "25"

GoogleCalcStepDefinition.java

@Ignore
public class GoogleCalcStepDefinition extends DemoApplicationTests {

    WebDriver driver;
    GoogleSearchPage googleSearchPage;

    @Given("^I open Google$")
    public void I_open_google() {
        this.driver = BrowserConfig.getWebDriver();
        this.googleSearchPage = PageFactory.initElements(driver, GoogleSearchPage.class);
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.get("https://www.google.com");
    }

    @When("^I enter \"([^\"]*)\" in search textbox$")
    public void I_enter_in_search_textbox(String additionTerms) {
        googleSearchPage.searchBox.sendKeys(additionTerms); //passing 2+2 here
        googleSearchPage.searchBtn.click();
    }

    @Then("^I should get result as \"([^\"]*)\"$")
    public void I_should_get_correct_result(String expectedResult) {
        String result = googleSearchPage.calculatorTextBox.getText();
        assertEquals(result, expectedResult); //Verify that result of 2+2 is 4
        BrowserConfig.releaseResources(driver);
    }

    @When("^I enter \"([^\"]*)\" in search textbox$")
    public void I_enter_in_search_textbox2(String multiplicationTerms) {
        googleSearchPage.searchBox.sendKeys(multiplicationTerms); //passing 5*5 here
        googleSearchPage.searchBtn.click();
    }

    @Then("^I should get result as \"([^\"]*)\"$")
    public void I_should_get_correct_result2(String expectedResult) {
        String result = googleSearchPage.calculatorTextBox.getText();
        assertEquals(result, expectedResult); //Verify that result of 5*5 is 25
        BrowserConfig.releaseResources(driver);
    }
}   

DemoApplicationTests.java

@RunWith(SpringRunner.class)
@SpringBootTest
public abstract class DemoApplicationTests {

}

GoogleSearchPage.java

public class GoogleSearchPage {

    @FindBy(name = "q")
    public WebElement searchBox;
    @FindBy(name = "btnK")
    public WebElement searchBtn;
    @FindBy(id = "cwos")
    public WebElement calculatorTextBox;

}

TestRunner.java

@RunWith(Cucumber.class)
@CucumberOptions(
        plugin = {"pretty", "json:target/cucumber-reports/cucumber.json"},
        glue = {"com.example.stepdefs"},
        features = {"src/test/resources/features"})
public class TestRunner {

}

Answer:

You have two gherkin steps that are identical save for the numeric value, and the numeric value was parameterized out with Regex, leaving them completely identical. So while the two steps in the gherkin are unique, the bindings in the step definition are duplicates:

@Then("^I should get result as \"([^\"]*)\"$")

and

@Then("^I should get result as \"([^\"]*)\"$")

Same for the two When steps. You can either replace the Regex with the same hardcoded values as the gherkin (probably not what you want), or simply delete the duplicates since the steps look like they're properly handling the input argument. Once the dups are deleted, the two steps in the gherkin will both map to the single remaining step def.

Question:

Environment: Java/IntelliJ/Cucumber

Lately, I'v experienced several times that IntelliJ claims an ambiguous step definition when there doesn't appear to be one.

cucumber.runtime.AmbiguousStepDefinitionsException: "that "saken" is a 
rejected case in kommune "5000"" matches more than one step definition:
"^that "([^"]*)" is a rejected case" in SakSteps.isARejectedCase(String)
"^that "([^"]*)" is a rejected case in kommune "([^"]*)"$" in 
SakSteps.isARejectedCaseInKommune(String,String)

The "Given" step text is not the same, although the first 6 strings match:

"^that "([^"]*)" is a rejected case"
"^that "([^"]*)" is a rejected case in kommune "([^"]*)"$"

The method names are not at all similar:

isARejectedCase(String)
isARejectedCaseInKommune(String,String)

How come IntelliJ/Cucumber claims that these are ambiguous?

This code did work before. There may have been some plugin update or other in between, but I don't see why it should behave like this?


Answer:

Answring my own post here:

The reason was a missing "$" at the end of the step definition, to mark the end of the sentence. Without that, it will match definitions that start with the same words. Example:

When X does Y because of W
When X does Y becayse of W in addition to P

Question:

I Am New To java-cucumber. Getting This Error:

cucumber.runtime.CucumberException: Couldn't load plugin class: json-pretty

Caused by: java.lang.ClassNotFoundException: json-pretty

@RunWith(Cucumber.class)
@CucumberOptions(
        plugin={"pretty", "html:target/cucumber-htmlreport", "json-pretty:target/cucmber-report.json"})

public class CucumberTest {
//codes
}

Answer:

Seems you were pretty close.

You need to change the plugin definations as follows:

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class) 
@CucumberOptions( plugin={"pretty:target/cucumber-htmlreport.text", "json:target/cucmber-report.json"})

public class CucumberTest { //codes }

Question:

I develop a test for the mobile application using Cucumber+Junit+Appium. When I try to run a test using cucumber and JUnit runner I receive: io.cucumber.junit.UndefinedStepException: The step "I install the application" is undefined. You can implement it using the snippet(s) below:

I tried some of the solutions from the medium blog and stack question, but this doesn't help.

I have a project structure:

src
 |-main
 |--java
 |---{project-name}
 |----config
 |----models
 |----screens
 |----services
 |-test
 |--java
 |---{project-name}
 |----helpers
 |----stepDefinitions
 |-----LoginStep.java
 |-----BaseStep.java
 |-----LoginStep.java
 |----RunCucumber.java
 |--resources
 |---feature
 |----Login.feature 

RunCucumber.java

package com.mobile.automation.framework;

import com.google.inject.Guice;
import com.mobile.automation.framework.module.ServiceModules;
import com.mobile.automation.framework.service.AppiumServer;
import com.mobile.automation.framework.config.drivers.DriverFactory;
import com.mobile.automation.framework.module.ScreensModule;
import io.appium.java_client.AppiumDriver;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
        strict = true,
        monochrome = true,
        glue = "src.test.java.com.mobile.automation.framework.stepDefinition",
        features = "src/test/resources/feature",
        plugin = {"pretty", "html:target/cucumber-report/cucumber.html",
                "json:target/cucumber-report/cucumber.json",
                "junit:target/cucumber-report/cucumber.xml"})
public class RunCucumber {
    public static AppiumDriver driver;

    @Before
    public void setUpDriver() {
        init();
        new AppiumServer().startServer();
        driver = new DriverFactory().getDriver();
    }

    @After
    public void tearDownDriver() {
        if (driver != null) {
            driver.quit();
            new AppiumServer().stopServer();
        }
    }

    private void init() {
        Guice.createInjector(
                new ScreensModule(driver),
                new ServiceModules(driver)
        ).injectMembers(this);
    }
}

Login.feature

Feature: Sign In feature

  Background:
    Given I install application
    And I enable all network activity
    Then I am on Sign Page

  Scenario: Sign In scenario
    Given I am go to the Login Page
    And I fill valid user data using "Config"
    And I click sign in button

    Then I am login in the application

LoginStep.java

package com.mobile.automation.framework.stepDefinition;

import javax.inject.Inject;

import com.mobile.automation.framework.config.ProjectConfig;
import com.mobile.automation.framework.models.User;
import com.mobile.automation.framework.screens.DashboardScreen;
import com.mobile.automation.framework.screens.SignInScreen;
import io.cucumber.java.ParameterType;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;

/**
 * @author Tomash Gombosh
 */
public class LoginStep {
    @Inject
    private SignInScreen signInScreen;
    @Inject
    private DashboardScreen dashboardScreen;

    @Given("^I am go to the Login Page$")
    public void iAmGoToTheLoginPage() {
        dashboardScreen.tapLogin();
    }

    @And("I fill valid user data using {string} {string}")
    public void iFillValidUserDataUsing(String userName, String password) {
        signInScreen.fillLogin(userName, password);
    }

    @And("I fill valid user data using {string}")
    @ParameterType("Config")
    public void iFillValidUserDataUsing() {
        signInScreen.fillLogin(new User(data -> {
            data.setEmail(new ProjectConfig().getBaseUser());
            data.setPassword(new ProjectConfig().getBaseUserPassword());
        }));
    }

    @And("I click sign in button")
    public void iClickSignInButton() {
        signInScreen.clickLogin();
    }

    @Then("I am login in the application")
    public void iAmLoginInTheApplication() {
        assertThat(signInScreen.isDisplayed()).isEqualTo(true);
    }

}

Some of the steps on the Login class is missing, but that is because I want to put all the code to the question.

I expected to run that feature, but actually that is not work.


Answer:

Typically src.test.java is not part of the package name. Try using:

glue = "com.mobile.automation.framework.stepDefinition",

And because Cucumber will search the runners package for glue by default can also remove the glue entirely.

Question:

I am receiving the following NullPointerException when trying to execute a Cucumber StepDefs file that passes a JSON from a .feature file to a REST endpoint on localhost;

  • I have tried to instantiate the ResultActions in every other way, receiving the same error.

  • The Controller works linked to the test is fine, and is pointing to the correct REST endpoint.

  • The issue is with the result in personStepDefs

  • I don't think I'm missing a parameter for ResultActions result as I've built my RequestBuilder
java.lang.NullPointerException at com.///.v2.PersonStepDefs.i\_add\_a\_new\_Person\_using\_POST\_at\_with\_JSON([PersonStepDefs.java:49](https://PersonStepDefs.java:49)) at

✽.I add a new Person using POST at "[http://localhost:8080/services/person/add](http://localhost:8080/services/person/add)" with JSON:(file:///C:/path/to/src/test/resources/Person.feature:6)

PersonStepDefs.java

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;

@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration
@Transactional
/**
 * Person Step Definition class to execute Scenario contained in Person.feature
 * @author Lewis Jones
 *
 */
public class PersonStepDefs {

    @Autowired
    private volatile WebApplicationContext wac;

    @Autowired
    private volatile MockMvc mockMvc;

    private ResultActions result;

    /**
     * Runs the application server before every scenario.
     */
    @BeforeClass
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @When("I add a new Person using POST at {string} with JSON:")
    public void i_add_a_new_Person_using_POST_at_with_JSON(String request, String json) throws Exception {
        result = mockMvc.perform(post(request).contentType(MediaType.APPLICATION_JSON)
                .content(json.getBytes()));
    }

    @Then("the response code should be {int}")
    public void the_response_code_should_be(Integer responseCode) throws Exception {
        result.andExpect(status().is(responseCode));
    }

}

RunMvcTest.java

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@RunWith(Cucumber.class)
@CucumberOptions(
        plugin = {"pretty","html:build/cucumber-html-report"},
        features = "src/test/resources", strict = true)
@WebAppConfiguration
@ContextConfiguration(classes = V2Application.class)
/**
 * A class to run the Cucumber .feature files located in 'features'
 * @author Lewis Jones
 *
 */
public class RunMvcTest {

}

Person.feature

Feature: Person CRUD
  As a User, I want to add a Person

  @repo
  Scenario: Person.Repo.Add
    When I add a new Person using POST at "http://localhost:8080/services/person/add" with JSON:
      """
      {"firstName":"Lewis","lastName":"Jones","addressId":"1", "dob":"1999-07-11"}
      """
    Then the response code should be 200

Answer:

A null pointer exception happens when you try to de-reference a variable or field that is null. So if you try to call perform on mockMvc while mockMvc is null you will get a null pointer exception.

If you read the stack trace carefully you can see that this it what it tries to tell you.

result = mockMvc.perform(....);

So how can mockMcv be null? You initialize it in setup method right? That means setup isn't called. You can confirm this by putting a break point in the method and debugging your test.

import org.junit.BeforeClass;

....

    /**
     * Runs the application server before every scenario.
     */
    @BeforeClass
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

And setup doesn't get called because BeforeClass is a JUnit annotation. Cucumber uses io.cucumber.java.Before.

Question:

I don't know if this question has been asked/answered yet. If so, I'm sorry. But I'm new to IntelliJ and there's a lot of foreign words I yet need to understand.

My problem is as follows: I installed the complete IntelliJ package, created a new Java project and created a new class inside my src folder:

package de.itsme.hello;

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

So I try to run it and I get this Error:

Error: Could not find or load main class cucumber.api.cli.Main
Caused by: java.lang.ClassNotFoundException: cucumber.api.cli.Main

I tried adding cucumber-core:4.0.1 to the project's dependencies but then I got another exception:

Exception in thread "main" cucumber.runtime.CucumberException: No backends were found. Please make sure you have a backend module on your CLASSPATH.
at cucumber.runtime.BackendModuleBackendSupplier.get(BackendModuleBackendSupplier.java:39)
at cucumber.runner.SingletonRunnerSupplier.createRunner(SingletonRunnerSupplier.java:38)
at cucumber.runner.SingletonRunnerSupplier.get(SingletonRunnerSupplier.java:32)
at cucumber.runtime.Runtime.run(Runtime.java:75)
at cucumber.api.cli.Main.run(Main.java:26)
at cucumber.api.cli.Main.main(Main.java:8)

I don't need cucumber or at least not for now. Is there a way to make it either work or remove it from the project?

Thanks in advance!


Answer:

Maybe you have the packet JDK installed incorrectly and this produces you an error. Or maybe your classspath is incorrect.

Question:

I am using eclipse to run cucumber feature and I got this error.I have installed java 11.0.4.

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by cucumber.runtime.java8.ConstantPoolTypeIntrospector (file:/Users/test1/.m2/repository/info/cukes/cucumber-java8/1.2.5/cucumber-java8-1.2.5.jar) to method java.lang.Class.getConstantPool()
WARNING: Please consider reporting this to the maintainers of cucumber.runtime.java8.ConstantPoolTypeIntrospector
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Exception in thread "main" cucumber.runtime.CucumberException: Failed to instantiate class test.sample.cucumber.steps.TestAPISteps
    at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:47)
    at cucumber.runtime.java.DefaultJavaObjectFactory.getInstance(DefaultJavaObjectFactory.java:33)
    at cucumber.runtime.java.JavaBackend.buildWorld(JavaBackend.java:131)
    at cucumber.runtime.Runtime.buildBackendWorlds(Runtime.java:141)
    at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:38)
    at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
    at cucumber.runtime.Runtime.run(Runtime.java:122)
    at cucumber.api.cli.Main.run(Main.java:36)
    at cucumber.api.cli.Main.main(Main.java:18)
Caused by: java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
    at cucumber.runtime.java.DefaultJavaObjectFactory.cacheNewInstance(DefaultJavaObjectFactory.java:41)
    ... 8 more
Caused by: java.lang.NoClassDefFoundError: sun/reflect/ConstantPool
    at cucumber.runtime.java8.ConstantPoolTypeIntrospector.getGenericTypes(ConstantPoolTypeIntrospector.java:29)
    at cucumber.runtime.java.Java8StepDefinition.getParameterInfos(Java8StepDefinition.java:54)
    at cucumber.runtime.java.Java8StepDefinition.<init>(Java8StepDefinition.java:44)
    at cucumber.runtime.java.JavaBackend.addStepDefinition(JavaBackend.java:162)
    at cucumber.api.java8.En.Given(En.java:199)
    at com.cbre.host.foodandbeverages.cucumber.steps.ProductStoreApiSteps.<init>(ProductStoreApiSteps.java:40)
    ... 13 more
Caused by: java.lang.ClassNotFoundException: sun.reflect.ConstantPool
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 19 more

What could be the reason of this ? This is happening only on my machine. On other machines, this issue is not replicated. I have tried updating maven project. Tried and got the same issue on STS as well.

Both machine are having same java installed ..

java version "11.0.4" 2019-07-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.4+10-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.4+10-LTS, mixed mode)

Answer:

You are currently using Cucumber JVM 1.2.5. This version of Cucumber can't run on Java 9 or higher. You may want to consider upgrading.

The latest released version of Cucumber JVM is 4.8.0. Note that the groupId has changed from info.cukes to io.cucumber.

Question:

I'm trying to automatize a web datatable testing. I'm getting this NullPointerException in every WebElement object i'm using to locate. My code is simple as possible:

public class tableTestStepDefs {

@FindBy(how = How.XPATH, using = "//*[@id=\"contenido-table\"]/tbody/tr[1]/td[3]")
public WebElement cell1;
@FindBy(how = How.ID, using = "\"DTE_Field_sufijo\"")
public WebElement editableCell1;

@When("^i click on cell1 to make it editable$")
public void hagoClickEnUnaCeldaDeLaColumnaSufijo(){
driver.get("http://192.168.242.104:7777/some/context");
cell1.click();
}

I'm getting NullPointerException in every object, instead of NoSuchElementException wich is the one I usually get when the driver cannot find some element, while the driver is properly entering the page. If i debug, i can locate all the elements with the same id or xpath expression in the driver's instance. No idea whats going on

Here is the HTML part:

<div class="dataTables_scrollBody ps-container ps-theme-default ps-active-x" data-ps-id="77fa0bd8-5ef4-1c4e-e67a-a8675b515900" style="position: relative; overflow: auto; width: 100%; height: 762px;">
    <table id="contenido-table" class="table table-condensed table-striped dataTable no-footer" role="grid" aria-describedby="contenido-table_info" style="width: 2072px;">
        <thead>
            <tr role="row" style="height: 0px;">
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 112px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="ICAO Aerolinea: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">ICAO Aerolinea</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 43px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Vuelo: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Vuelo</div>
                </th>
                <th class="text-center editable sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 43px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Sufijo: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Sufijo</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 71px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Matricula: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Matricula</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 33px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Tipo: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Tipo</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 72px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Aeronave: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Aeronave</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 72px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Categoria: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Categoria</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 52px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Origen: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Origen</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 96px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Escala Previa: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Escala Previa</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 96px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Estado Vuelo: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Estado Vuelo</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 139px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Fecha Programada: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Fecha Programada</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 116px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Fecha Estimada: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Fecha Estimada</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 93px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Fecha Actual: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Fecha Actual</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 58px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Servicio: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Servicio</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 44px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Stand: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Stand</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 47px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Cintas: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Cintas</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 91px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Inicio Cintas: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Inicio Cintas</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 73px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Fin Cintas: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Fin Cintas</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 115px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Primera Maleta: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Primera Maleta</div>
                </th>
                <th class="text-center sorting" aria-controls="contenido-table" rowspan="1" colspan="1" style="width: 107px; padding-top: 0px; padding-bottom: 0px; border-top-width: 0px; border-bottom-width: 0px; height: 0px;" aria-label="Ultima Maleta: Activar para ordenar la columna de manera ascendente">
                    <div class="dataTables_sizing" style="height: 0px; overflow: hidden;">Ultima Maleta</div>
                </th>
            </tr>
        </thead>
        <tbody>
            <tr role="row" class="odd">
                <td class=" text-center" name="ICAO Aerolinea">DRA</td>
                <td class=" text-center" name="Vuelo">5485</td>
                <td class=" text-center editable" name="Sufijo"></td>
                <td class=" text-center" name="Matricula" style="display: table-cell;text-overflow: ellipsis;overflow: hidden;max-width: 195px;">GBC001</td>
                <td class=" text-center" name="Tipo" style="display: table-cell;text-overflow: ellipsis;overflow: hidden;max-width: 195px;">NA</td>
                <td class=" text-center" name="Aeronave">A001</td>
                <td class=" text-center" name="Categoria">C</td>
                <td class=" text-center" name="Origen">LEBB</td>
                <td class=" text-center" name="Escala Previa" style="display: table-cell;text-overflow: ellipsis;overflow: hidden;max-width: 195px;"></td>
                <td class=" text-center" name="Estado Vuelo">SCH</td>
                <td class=" text-center" name="Fecha Programada" style="min-width: 97px">03/10/2018</td>
                <td class=" text-center" name="Fecha Estimada"></td>
                <td class=" text-center" name="Fecha Actual"></td>
                <td class=" text-center" name="Servicio">A</td>
                <td class=" text-center" name="Stand"></td>
                <td class=" text-center" name="Cintas"></td>
                <td class=" text-center" name="Inicio Cintas"></td>
                <td class=" text-center" name="Fin Cintas"></td>
                <td class=" text-center" name="Primera Maleta"></td>
                <td class=" text-center" name="Ultima Maleta"></td>
            </tr>
            <tr role="row" class="even">
                <td class=" text-center" name="ICAO Aerolinea">AAA</td>
                <td class=" text-center" name="Vuelo">1234</td>
                <td class=" text-center editable" name="Sufijo"></td>
                <td class=" text-center" name="Matricula" style="display: table-cell;text-overflow: ellipsis;overflow: hidden;max-width: 195px;">GBC001</td>
                <td class=" text-center" name="Tipo" style="display: table-cell;text-overflow: ellipsis;overflow: hidden;max-width: 195px;">NA</td>
                <td class=" text-center" name="Aeronave">A001</td>
                <td class=" text-center" name="Categoria">C</td>
                <td class=" text-center" name="Origen">LEBB</td>
                <td class=" text-center" name="Escala Previa" style="display: table-cell;text-overflow: ellipsis;overflow: hidden;max-width: 195px;"></td>
                <td class=" text-center" name="Estado Vuelo">SCH</td>
                <td class=" text-center" name="Fecha Programada" style="min-width: 97px">03/10/2018</td>
                <td class=" text-center" name="Fecha Estimada"></td>
                <td class=" text-center" name="Fecha Actual"></td>
                <td class=" text-center" name="Servicio">A</td>
                <td class=" text-center" name="Stand"></td>
                <td class=" text-center" name="Cintas"></td>
                <td class=" text-center" name="Inicio Cintas"></td>
                <td class=" text-center" name="Fin Cintas"></td>
                <td class=" text-center" name="Primera Maleta"></td>
                <td class=" text-center" name="Ultima Maleta"></td>
            </tr>
        </tbody>
    </table>
    <div class="ps-scrollbar-x-rail" style="width: 2063px; left: 0px; bottom: 3px;">
        <div class="ps-scrollbar-x" tabindex="0" style="left: 0px; width: 2055px;"></div>
    </div>
    <div class="ps-scrollbar-y-rail" style="top: 0px; right: 3px;">
        <div class="ps-scrollbar-y" tabindex="0" style="top: 0px; height: 0px;"></div>
    </div>
</div>

Answer:

You are missing initialization of PageFactory, that's why you get NullPointerException instead of NoSuchElementException

Add constructor like this:

public class tableTestStepDefs {

@FindBy(how = How.XPATH, using = "//*[@id=\"contenido-table\"]/tbody/tr[1]/td[3]")
public WebElement cell1;
@FindBy(how = How.ID, using = "\"DTE_Field_sufijo\"")
public WebElement editableCell1;

public tableTestStepDefs() { //this!
    PageFactory.initElements(driver, this);
}

@When("^i click on cell1 to make it editable$")
public void hagoClickEnUnaCeldaDeLaColumnaSufijo(){
driver.get("http://192.168.242.104:7777/some/context");
cell1.click();
}

Question:

Hi community: I am stuck in the next issue:

java.lang.NullPointerException
    at pages.Page_First.getURL(Page_First.java:31)
    at stepdefs.Step_First.I_go_to_Google(Step_First.java:22)
    at ✽.I go to Google (src/test/resources/features/first.feature:9)

This is my Feature:

Feature: Navigation Test

  As a user, bla, bla, bla...

  Scenario: Search google.com to verify google search is working

    Given I go to Google
    When I query for "<search>" cucumber spring selenium
    And click search
    Then google page title should become the first page

This next is my DriverClass

public class DriverClass implements Constants {

    // Take the instance of WebDriver
    protected static WebDriver driver;

    //Initialize a log
    protected static final Logger log = Logger.getLogger(BasePage.class.getName());


    public static WebDriver initializeDriver() throws IOException {

        String browser = ReadProperties.getPropertyValue(key_browser);


        if(browser.equals("chrome")) {
            WebDriverManager.chromedriver().setup();
            driver = new ChromeDriver();

        } else if(browser.equals("firefox")) {
            WebDriverManager.firefoxdriver().setup();
            driver = new FirefoxDriver();

        } else if(browser.equals("ie")) {
                WebDriverManager.iedriver().setup();
                driver = new InternetExplorerDriver();

        } else if(browser.equals("edge")) {
            WebDriverManager.edgedriver().setup();
            driver = new EdgeDriver();

        } else {
            System.setProperty("webdriver.safari.driver","/usr/bin/safaridriver");
            driver = new SafariDriver();
        }
        return driver;
    }
}

This other is my DriverInitializer Class

public class DriverInitializer extends DriverClass {


    @Before
    public void initialize() throws IOException {

        log.info("-----> Proceed to initialize driver <-----");

        driver = DriverClass.initializeDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.manage().window().maximize();

        if (driver == null) {
            log.info("-----> Driver did not initialize correctly <-----");
        }
    }

    @After
    public void close(){
        driver.quit();
    }
}

My Page Class:

public class Page_First extends BasePage implements Constants {

    public Page_First() {
        PageFactory.initElements(driver, this); }


    //////////////////////////////////////////////WEB ELEMENTS//////////////////////////////////////////////////////////

    @FindBy(name = "q")
    private WebElement searchText;

    @FindBy(name="btnK")
    private WebElement searchButton;

    //////////////////////////////////////////////BASE METHODS//////////////////////////////////////////////////////////

    public void getURL() throws IOException {

        String url = ReadProperties.getPropertyValue(key_url);
        driver.get(url);

And My Step Definition:

public class Step_First {

    public static WebDriver driver;
    private Page_First page_first = PageFactory.initElements(driver, Page_First.class);


    @Given("I go to Google")
    public void I_go_to_Google () throws IOException {

        page_first.getURL();
    }

I know that the problem is in the next pice of code (Page):

String url = ReadProperties.getPropertyValue(key_url);
driver.get(url);

By the way: This is my Constants class

public interface Constants {

String key_url = "url";
String key_browser = "browser";

}

Please, I need your help. Thanks in advance

Updated: This is my file for reading property files:

public class ReadProperties {

    public static final String filePath = "src/main/resources/data/config.properties";


    public static String getPropertyValue(String key) throws IOException {
        Properties prop = new Properties();
        FileInputStream fis = new FileInputStream(filePath);
        prop.load(fis);
        fis.close();
        return prop.getProperty(key);
    }
}

Answer:

May be it doesn't find your path. Try this:

public class ReadProperties {

    public static String getPropertyValue(String key) throws IOException {
        String filePath = "src/main/resources/data/config.properties";
        InputStream input = new FileInputStream(filePath);
        Properties prop = new Properties();

        try (input) {
            prop.load(input);
            return prop.getProperty(key);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Question:


Answer:

The driver that has been initialized in the ConfigFileReader class needs to be passed to the stepdefinition class to initialize the driver variable of that class.

Add the last line to the stepdefinition given method.

@Given("^User is on Homepage$")
public void user_is_on_Homepage() throws Throwable {

    ConfigFileReader cnffilered= new ConfigFileReader();
    cnffilered.getBrowserType();
    cnffilered.getUrl();
    cnffilered.Implicitwait();
    cnffilered.MaxmimizeWindow();
    **this.driver = cnffilered.getDriver();**
}

Add method getDriver() in class ConfigFileReader

public WebDriver getDriver() {
    return driver;
}

If they are in the same package make the driver variable in ConfigFileReader protected and access it directly without need for a driver variable in the stepdefinition class.

Question:

I'm trying to run cucumber test,but i'm getting the following exception. I used those jars with their versions

And this is my project :

And this is testRunner class code :

    package cucumberTest;

import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "Feature"
        ,glue={"stepDefinition"}
        )

        public class TestRunner {

        }

In the logIn.feature file :

Feature: Login Action Test

Scenario: Successful Login with Valid Credentials Given User is on Home Page When User Navigate to LogIn Page And User enters UserName and Password Then Message displayed Login Successfully

Scenario: Successful LogOut When User LogOut from the Application Then Message displayed LogOut Successfully


Answer:

According to this, cucumber-java-1.2.5 requires gherkin-2.12.2, while I was providing gherkin-4.1.13

So I downloaded version 2.12.2 from here, removed version 4.1.13 and it worked for me (I did a clean to the project).

Question:

I'm gettin the AmbiguousStepDefinitionsException with the log:

cucumber.runtime.AmbiguousStepDefinitionsException: ✽.Given I am logged out(features/performance.feature:7) matches more than one step definition:
^I am logged out$ in PerformanceListSteps.i_am_logged_out()
^|I should be on |the list page$ in LoginSteps.i_should_be_on_the_list_page()

While running the cucumber tests. I'm kinda fresh with this attitude and I'd be really glad for help.


Answer:

The problem lies in the second regex pattern:

^|I should be on |the list page$

The pipe (|) symbol is an alteration. So this regex basically means it will match one of the alternatives:

  • an empty string (on the left of first |)
  • I should be on
  • the list page

A regex matching an empty string will can match 0 characters, so it will match against any string. This somewhat depends on the implementation, but in the case of Cucumber-JVM I confirmed that if I added a similar regex pattern to one of my step definitions, it matched against all steps in the project.

Solution

The best solution here would be to remove the pipes from the regex, as (usually) you want the regex to be as specific as possible, leaving variations only for variables that go into the step definition.

So what you need here is to change the regex pattern to:

^I should be on the list page$

It will match steps with that statement following any of the Gherkin keywords (Given/When/Then etc.), e.g.:

Then I should be on the list page

Question:

I am working on a Selenium Project where the Workspace name I was using had a space because of which I was getting following error:

Exception in thread "main" java.lang.IllegalArgumentException: C:/Users/xyz/eclipse-workspace ValveAware/TestProject/src/test/resources/features/Administration/Export.feature is not valid. Try URI[:LINE]*
    at io.cucumber.core.model.FeatureWithLines.parse(FeatureWithLines.java:56)
    at cucumber.runtime.RuntimeOptions.parse(RuntimeOptions.java:189)
    at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:107)
    at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:100)
    at cucumber.runtime.RuntimeOptions.<init>(RuntimeOptions.java:96)
    at cucumber.runtime.Runtime$Builder.withArgs(Runtime.java:131)
    at cucumber.runtime.Runtime$Builder.withArgs(Runtime.java:127)
    at cucumber.api.cli.Main.run(Main.java:22)
    at cucumber.api.cli.Main.main(Main.java:8)
Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 36: C:/Users/xyz/eclipse-workspace ValveAware/TestProject/src/test/resources/features/Administration/Export.feature
    at java.base/java.net.URI.create(URI.java:883)
    at io.cucumber.core.model.FeaturePath.parseProbableURI(FeaturePath.java:44)
    at io.cucumber.core.model.FeaturePath.parse(FeaturePath.java:37)
    at io.cucumber.core.model.FeatureWithLines.parseFeaturePath(FeatureWithLines.java:77)
    at io.cucumber.core.model.FeatureWithLines.parse(FeatureWithLines.java:53)
    ... 8 more
Caused by: java.net.URISyntaxException: Illegal character in path at index 36: C:/Users/xyz/eclipse-workspace ValveAware/TestProject/src/test/resources/features/Administration/Export.feature
    at java.base/java.net.URI$Parser.fail(URI.java:2915)
    at java.base/java.net.URI$Parser.checkChars(URI.java:3086)
    at java.base/java.net.URI$Parser.parseHierarchical(URI.java:3168)
    at java.base/java.net.URI$Parser.parse(URI.java:3116)
    at java.base/java.net.URI.<init>(URI.java:600)
    at java.base/java.net.URI.create(URI.java:881)
    ... 12 more

I changed the name of the workspace and removed the space. I checked the path of the file Export.feature and the space is not there. But when I execute this file, I am still getting the same error.

Runner File:

package valveAware.port.localhost.tests;

import cucumber.api.CucumberOptions;
import cucumber.api.testng.AbstractTestNGCucumberTests;

@CucumberOptions(
        features = { "src/test/resources/features/Administration/Export.feature" }, 
        monochrome = true,
        plugin = { "pretty","html:target/Destination" }, 
        glue = { "valveAware.port.localhost.tests" }
        )



public class ValveAwareRunnerTest extends AbstractTestNGCucumberTests{

}

Answer:

I created a new workspace and imported the projects, then it worked

Question:

I'm new to cucumber. when i'm trying to run the feature files separately i'm getting no Feature found Exception. i tried all the suggestions from the already asked questions in StackOverflow but those are not worked for me. please help me to solve this issue.

My Feature File

Feature: CucumberJava

  Scenario: Logging in to Facebook using DataTables
    Given I have open the "Chrome" browser
    When I open Facebook website
    And Logging in to Facebook using DataTables
      | Feild               | Values              |
      | Email id            | fsferr@dsgs.com     |
      | Password            | dvfsgg              |
    Then Click on Login button

My Runner file

package cucumberPackage;

import org.junit.runner.RunWith; 
import cucumber.junit.Cucumber; 

@RunWith(Cucumber.class) 
//@Cucumber.Options(format = {"pretty", "html:target/cucumber"}) 
@Cucumber.Options(features="src/test/resources/demo/DataTables.feature",format = {"pretty", "html:target/cucumber"}) 
public class RunnerTest {

}

Error Log

cucumber.runtime.CucumberException: No features found at [src/test/resources/demo/DataTables.feature]
    at cucumber.runtime.model.CucumberFeature.load(CucumberFeature.java:47)
    at cucumber.runtime.RuntimeOptions.cucumberFeatures(RuntimeOptions.java:82)
    at cucumber.junit.Cucumber.<init>(Cucumber.java:60)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
    at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Answer:

Following assumption is made

  • you are using Cucumber version <= 1.1.8 (because of your use of @Cucumber.Options, which has been removed in version 1.2.0, the current Cucumber release is 3.0.2, maybe think about updating to a recent version
  • the following files exists in the current directory

    src/test/java/cucumberPackage/RunnerTest.java
    src/test/resources/demo/DataTables.feature
    pom.xml
    

RunnerTest.java

as in your post, with fixed import statement for Cucumber.class

// import cucumber.junit.Cucumber;
import cucumber.api.junit.Cucumber;

DataTables.feature

as in your post

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.suboptimal</groupId>
    <artifactId>cuke-test.so</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <version.cucumber>1.1.8</version.cucumber>
    </properties>
    <dependencies>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${version.cucumber}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>${version.cucumber}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</project>

running the test with mvn test executes you scenario

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running cucumberPackage.RunnerTest
Feature: CucumberJava

  Scenario: Logging in to Facebook using DataTables # src/test/resources/demo/DataTables.feature:3
    Given I have open the "Chrome" browser
    When I open Facebook website
    And Logging in to Facebook using DataTables
    Then Click on Login button

1 Scenarios (1 undefined)
4 Steps (4 undefined)
0m0.000s


You can implement missing steps with the snippets below:
...

Question:


Answer:

You need to add the following dependency to your POM. The class is contained inside this jar.

<dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-jvm-deps</artifactId>
    <version>1.0.6</version>
</dependency>

If not using Maven download this at https://mvnrepository.com/artifact/io.cucumber/cucumber-jvm-deps/1.0.6 and add to build path.

Question:

Hi community: Trying to integrate Cucumber with JUnit, I have the next class.

import cl.cukes.ParameterizedRunnerFactory;
import cl.test.AutomatedWebTest;
import cl.util.report.Report;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
import org.junit.runner.Runner;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.UseParametersRunnerFactory;
import org.junit.runners.model.InitializationError;
import org.junit.runners.parameterized.TestWithParameters;
import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

//JAVA

@RunWith(Parameterized.class)
@UseParametersRunnerFactory(ParameterizedRunnerFactory.class)
public class CucumberStepDefs extends AutomatedWebTest {

    @Parameterized.Parameter(value = 0)
    public String user;
    @Parameterized.Parameter(value = 1)
    public String pass;


   public static class CucumberRunnerFactor extends ParameterizedRunnerFactory {

       public Runner createRunnerForTestWithParameters(TestWithParameters test)
               throws InitializationError {
           try {
               return new Cucumber(test.getTestClass().getJavaClass());
           } catch (IOException e) {
               throw new InitializationError(e);
           }
       }
    }
    @Given("^Enter to the QA URL environment")
    public void Login() throws Exception {

        baseUrl = "http://www.miprivado.cl/";
        driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        driver.get(baseUrl + "ucachaca/test.htm");
        driver.switchTo().defaultContent();
        driver.switchTo().frame("frmbody");
    }

    @When("^Fields Username y Passwordare displayed so enter parameters$")
    public void UsuarioPass() throws Exception {
        driver.findElement(By.id("TxbTELLUSERID")).clear();
        driver.findElement(By.id("TxbTELLUSERID")).sendKeys(user);
        driver.findElement(By.id("TxbUSERPASSW")).clear();
        driver.findElement(By.id("TxbUSERPASSW")).sendKeys(pass);


        screenshot.take(this, driver, "LoginR C01");
        driver.findElement(By.id("BtnSubmit")).click();
        driver.switchTo().defaultContent();
        driver.switchTo().frame("frmwebteller");
        driver.manage().window().maximize();
    }

    @Then("^User gets into the system and do Logout Logout$")
    public void Logout() throws Exception {
        screenshot.take (this, driver, "LoginR C02");

        driver.switchTo ().defaultContent ();
        driver.switchTo ().frame ("frmbody").switchTo ().frame ("menu"); 

        driver.findElement(By.cssSelector("b")).click();
        screenshot.take (this, driver, "LoginR C03");

        driver.findElement(By.linkText("Log Off")).click();
        screenshot.take (this, driver, "LoginR C04");

        driver.quit();
    }

}

The ParameterizedRunnerFactory is the next:

import org.junit.runner.Runner;
import org.junit.runners.model.InitializationError;
import org.junit.runners.parameterized.ParametersRunnerFactory;
import org.junit.runners.parameterized.TestWithParameters;

/**
 *
 */
public class ParameterizedRunnerFactory implements ParametersRunnerFactory {
    @Override
    public Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
        return new ParameterizedRunner(test);
    }
}

The parameterized Runner class is the next:

import org.junit.After;
import org.junit.Before;
import org.junit.runners.model.*;
import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;
import org.junit.runners.parameterized.TestWithParameters;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class ParameterizedRunner extends BlockJUnit4ClassRunnerWithParameters {
        public ParameterizedRunner(TestWithParameters test) throws InitializationError {
            super(test);
        }

        // workaround for: https://github.com/junit-team/junit/issues/1046
        private static final ConcurrentHashMap<Class<?>, TestClass> testClasses = new ConcurrentHashMap<>();

        @Override
        protected TestClass createTestClass(Class<?> clazz) {
            TestClass testClass = testClasses.get(clazz);
            if (testClass == null) {
                testClasses.put(clazz, testClass = new TestClass(clazz));
            }
            return testClass;
        }

        // playing whack-a-mole with new TLAB allocations by re-defining with{Befores,Afters}...

        @Override
        protected Statement withBefores(FrameworkMethod method, Object target, Statement statement) {
            List<FrameworkMethod> list = getTestClass().getAnnotatedMethods(Before.class);
            if (list.isEmpty()) {
                return statement;
            }
            return new BeforesStatement(target, statement, list);
        }

        @Override
        protected Statement withAfters(FrameworkMethod method, Object target, Statement statement) {
            List<FrameworkMethod> list = getTestClass().getAnnotatedMethods(After.class);
            if (list.isEmpty()) {
                return statement;
            }
            return new AftersStatement(target, statement, list);
        }

        private static final class BeforesStatement extends Statement {
            private static final Object[] EMPTY_ARGS = new Object[0];
            private final Object target;
            private final Statement statement;
            private final List<FrameworkMethod> list;

            BeforesStatement(Object target, Statement statement, List<FrameworkMethod> list) {
                this.target = target;
                this.statement = statement;
                this.list = list;
            }

            @Override
            public void evaluate() throws Throwable {
                // (1) Avoid ImmutableCollections#iterator()
                for (int i = 0, size = list.size(); i < size; ++i) {
                    list.get(i).invokeExplosively(target, EMPTY_ARGS);
                }
                statement.evaluate();
            }
        }

        private static final class AftersStatement extends Statement {
            private static final Object[] EMPTY_ARGS = new Object[0];
            private final Object target;
            private final Statement statement;
            private final List<FrameworkMethod> list;

            AftersStatement(Object target, Statement statement, List<FrameworkMethod> list) {
                this.target = target;
                this.statement = statement;
                this.list = list;
            }

            @Override
            public void evaluate() throws Throwable {
                // (2) Lazily create ArrayList
                ArrayList<Throwable> throwables = null;
                try {
                    statement.evaluate();
                } catch (Throwable e) {
                    throwables = new ArrayList<Throwable>();
                    throwables.add(e);
                } finally {
                    for (int i = 0, size = list.size(); i < size; ++i) {
                        try {
                            list.get(i).invokeExplosively(target, EMPTY_ARGS);
                        } catch (Throwable e) {
                            if (throwables == null) {
                                throwables = new ArrayList<Throwable>();
                            }
                            throwables.add(e);
                        }
                    }
                }
                if (throwables != null) {
                    MultipleFailureException.assertEmpty(throwables);
                }
            }
        }
    }

The Cucumber Runner Test class is the next:

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(features={"//src/features/Login.feature"}
                 ,format = {"pretty", "html:target/cucumber"}
                 ,glue = {"cucumber.CucumberStepDefs"}
)
/*@Suite.SuiteClasses({
        CucumberStepDefs.class,
})*/

public class CucumberRunnerTest {

}

When I run my CucumberStepDefs, it displays the next issue on IntelliJ:

java.lang.Exception: No public static parameters method on class cl.cucumber.CucumberStepDefs

All the classes don't show error, but I'm not able to run this class.

Could anybody help me with this?


Answer:

Don't try to mix JUnit with Maven:

The best answer were done by Grasshopper:

1.- Create the Feature file.

2.- Use Scenario Outline and put the data in Examples section.

3.- Use a runner like next:

    @CucumberOptions(features = {"src/test/resource/features"},
                 glue={"stepdefs"},
                 monochrome = true,
                 tags = {"~@Ignore"},
                 plugin = {"pretty","html:target/cucumber-reports/cucumber-pretty",
                           "json:target/cucumber-reports/CucumberTestReport.json",
                           "rerun:target/cucumber-reports/rerun.txt",
                           "usage:target/cucumber-usage.json"}
)
public class TestRunner extends ExtendedTestNGRunner{
    private TestNGCucumberRunner testNGCucumberRunner;

    @BeforeClass(alwaysRun = true)
    public void setUpClass() throws Exception {
        testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
    }

    @Test(groups = "cucumber", description = "Runs Cucumber Feature", dataProvider = "features")
    public void feature(CucumberFeatureWrapper cucumberFeature) {
        testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
    }

    @DataProvider
    public Object[][] features() {
        return testNGCucumberRunner.provideFeatures();
    }

    @AfterClass(alwaysRun = true)
    public void tearDownClass() throws Exception {
        testNGCucumberRunner.finish();
    }
}

And run the Feature.

Thanks a lot, Grasshopper!!!

Question:

I'm trying to run a Junit test from inside my java application.

this is the JUnit test file

import com.intuit.karate.cucumber.CucumberRunner;
import com.intuit.karate.cucumber.KarateStats;
import cucumber.api.CucumberOptions;
import static org.junit.Assert.assertTrue;
import org.junit.Test;

@CucumberOptions(tags = {"~@ignore"})
public class TestParallel {
    @Test
    public void testParallel() {
        KarateStats stats = CucumberRunner.parallel(getClass(), 5, "target/surefire-reports");
        assertTrue("scenarios failed", stats.getFailCount() == 0);
    }
}

When I try calling it from the main :

public static void main(String[] args) {
    JUnitCore junit = new JUnitCore();
    Result result = junit.run(TestParallel.class);
}

I get this error

java.lang.NoClassDefFoundError: com/intuit/karate/cucumber/CucumberRunner

Any idea how to fix this?


Answer:

You need to add the class that could not be found on your classpath. If using Maven, verify that your scope is correctly defined. It should not be <scope>provided</scope> for the scope, for instance.

Why do you call your classes from the static main()-context even?

If you really want to execute your tests like that, make sure that you remove the <scope>test</scope> for the cucumber stuff.

Question:

Hi Guys I am following Page Object Model in Java with Cucumber. I have following classes:

AbstractClass.java: Initiates the webdriver instance and serves as Master class for other object classes.

package ObjectRepository;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


/**
 * Hello world!
 *
 */
public class AbstractClass {
    public static WebDriver driver=null;
    Properties p = new Properties();   // create an object of properties

    public AbstractClass(WebDriver driver){
        this.driver=driver;

    }
    public void setup() throws IOException{

        // file input stream obect
        FileInputStream fi= new FileInputStream("C:\\Users\\sulemanmazhar\\Google Drive\\Automation Learning\\Java\\udemyWorkspace\\DebitCard_PageObject\\src\\test\\java\\Banking\\global.properties");
        p.load(fi); // load the properties
        if (p.getProperty("browser").contains("fireFox")){  // if browser in property file is firefox
            driver=new FirefoxDriver();         
        };  

        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    }



    public loginPage navigateToWelcomePage(){
        String url=p.getProperty("url");
        System.out.println(url);
        driver.navigate().to(url);
        return new loginPage(driver);
    }

    public String getTitle(){
        String title= driver.getTitle().trim();
        return title;
    }

    public void quitDriver(){
        driver.quit();
    }
}

loginPage.Java: Serves as Object repository class for login Page of my SUT. Inherits Abstract Class

      package ObjectRepository;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;


    /**
     * This class is within the object repository package
     * This package will contain all the objects which will
     * These objects will be stored and the will be accessed from the test/java folder


    public class loginPage extends AbstractClass 
        public loginPage(WebDriver driver){
            super(driver);

        }
        // all login page objects belong to this page
        By username = By.name("userName");   // object
        By password = By.name("password");
        By name= By.name("login");  
        By registerLink = By.linkText("REGISTER");
        By signInLink=By.linkText("SIGN-ON");

    // constructor passes a webdriver object    
        public flightFinder login(String userId,String passw){
            driver.findElement(username).sendKeys(userId);
            driver.findElement(password).sendKeys(passw);
            driver.findElement(name).click();

            return new flightFinder(driver);
           }


        public registerPage navigateToRegister() {

            driver.findElement(registerLink).click();
            return new registerPage(driver);
        }
        public loginPage navigateToSignOn(){
       driver.findElement(signInLink).click();
            return new loginPage(driver);   
        }
}

I also have registerPage.java,flighFinder.java which serves the same purpose as loginPage.java

I have corresponding test classes for each of the classes. The two classes I want to discuss are:

stepsDefiniton.java : This class contains most of the common methods that are applicable across different classes.

package TestClasses;

import java.io.IOException;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;

import ObjectRepository.flightFinder;
import ObjectRepository.loginPage;
import ObjectRepository.registerPage;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class StepsDefinition {

    WebDriver  driver;
    loginPage loginPage;
    //flightFinder flightFinder;
    registerPage registerPage;


    @Before
    public void setUp() throws IOException{
        System.out.println("Executing before method");

        loginPage = new loginPage(driver);
        loginPage.setup();
        loginPage.navigateToWelcomePage();
    }

    @After
    public void CloseDriver(){
        System.out.println("Executing after method");

        loginPage.quitDriver();
    }

    /* Shared steps */
    @Given("^I am on \"([^\"]*)\" page$")
    public void i_am_on_page(String page) {

    if(page.equalsIgnoreCase("sign-on")){
            loginPage=loginPage.navigateToSignOn();
        }   

    if(page.equalsIgnoreCase("register")){
        registerPage=loginPage.navigateToRegister();
        }   
        String Title =loginPage.getTitle();
        System.out.println("Actual page title is :"+ Title+" Expected Title is :"+page);
        Assert.assertTrue(Title.contains(page));

    }

    @When("^I click on \"([^\"]*)\" button$")
    public void i_click_on_button(String button) {
        if (button.equalsIgnoreCase("register")){
            registerPage=loginPage.navigateToRegister();    
        }
        else if(button.equalsIgnoreCase("sign-on")){
            loginPage=loginPage.navigateToSignOn();
        }
    }

    @Then("^I should be navigated to \"([^\"]*)\" page$")
    public void i_should_be_navigated_to_page(String page) {
        String Title =loginPage.getTitle().trim();
        System.out.println("Actual page is :"+Title +" Expected page is :"+page);
        Assert.assertTrue(Title.contains(page));
    }
}

LoginTest.Java : Is the Test class contains the code to test the logiN Page. package TestClasses;

import org.openqa.selenium.WebDriver;

import ObjectRepository.flightFinder;
import ObjectRepository.loginPage;
import ObjectRepository.registerPage;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;

public class LoginTest {
    //WebDriver  driver;
    loginPage loginPage;
    flightFinder flightFinder;
    registerPage registerPage;

    /* Login Page */
    @When("^I input my details as \"([^\"]*)\" and \"([^\"]*)\"$")
    public void i_input(String username, String password) {
        flightFinder=loginPage.login(username,password);

    }

    @Given("^I am logged in as \"([^\"]*)\" and \"([^\"]*)\"$")
    public void i_am_logged_in(String username, String password){
    flightFinder=loginPage.login(username,password);

    }
}

Ok my question is: When I execute the test all the tests within the StepsDefinition.java runs fine and as expectedly. As soon as it moves onto LoginTest.Java I get following error:

5 Scenarios ([31m3 failed[0m, [32m2 passed[0m)
16 Steps ([31m3 failed[0m, [36m5 skipped[0m, [32m8 passed[0m)
1m30.444s

java.lang.NullPointerException
    at TestClasses.LoginTest.i_am_logged_in(LoginTest.java:30)
    at ✽.Given I am logged in as "test" and "test"(featureFiles/flightFinder.feature:5)

java.lang.NullPointerException
    at TestClasses.LoginTest.i_input(LoginTest.java:23)
    at ✽.When I input my details as "test" and "test"(featureFiles/login.feature:12)

java.lang.NullPointerException
    at TestClasses.Register_Test.i_input_my_details(Register_Test.java:21)
    at ✽.When I input my details(featureFiles/register.feature:12)

What I think happening is, I am initiating the objects in stepsDefinition.Java class and as soon as the test moves onto another test class it is not carrying on with the previous state of the object.

If thats the case how can I pass on the state of one object to another? If not then where am I going wrong? Any help will be much appreciated.


Answer:

The WebDriver is instantiated in the abstract class.

In the loginPage.Java,registerPage.java,flighFinder.java you are using driver which is not instantiated or driver which is instantiated in the abstract class is not passed to these classes.

Solution can be Remove driver=new FirefoxDriver(); from the setup of Abstract class instead place that in LoginTest and pass the driver object during loginPage,registerPage object creation.

ex: WebDriver driver = new ChromeDriver(); loginPage loginpage = new loginPage(driver);

I have tried it worked.

Question:

I am comparing two List of Strings, which finish comparing successfully, but then after, I get a -

java.lang.IndexOutOfBoundsException: Index: 7, Size: 7
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at java.util.Collections$UnmodifiableList.get(Collections.java:1309)
at com.cucumber.CucumberWebGui.StepDefinitions.tableHeaders(StepDefinitions.java:254)
at ✽.Then table with id "content" has header values of(tableHeader.feature:9)

The first list I pass in from a cucumber feature file. The second I collect from the table headers at this website - "http://toolsqa.com/automation-practice-table/"

I have tried changing the for loop, but it doesn't help. I have read other people's same issue on Stack Overflow, but I cannot solve it. I don't know what to do.

Here is the code and feature file -

Code -

@SuppressWarnings("deprecation")
@Then("^table with id \"([^\"]*)\" has header values of$")
public void tableHeaders(String id, DataTable table) {

    java.util.List<java.util.List<String>> expectedHeaders = table.raw();

    WebElement container = driver.findElement(By.id(id));
    List<WebElement> allHeaders = container.findElements(By.tagName("th"));

    List<String> actualHeaders = new ArrayList<String>();
    for (WebElement header : allHeaders) {
        actualHeaders.add(header.getText());
    }

    for (int i = 0; i < actualHeaders.size(); i++) {
        Assert.assertEquals(expectedHeaders.get(i).get(0), actualHeaders.get(i));
    }
}

Feature File -

Scenario: Test Table Header assertion 
Then table with id "content" has header values of 

    | Structure |
    | Country | 
    | City |
    | Height | 
    | Built | 
    | Rank |
    | … |

Answer:

Probably because expectedHeaders has less elements than actualHeaders.