Search code examples
javaguicecucumber-jvm

Configuring cucumber-guice


I am trying to use DI in my step definitions. I have a module,

public class MyModule extends AbstractModule
{
    private final static MyInterface INSTANCE = new MyInterfaceImpl();

    @Override
    protected void configure()
    {
        bind(MyInterface.class).toInstance(INSTANCE);
    }
}

and want to inject this instance in the constructor of the step definitions.

public class MyStepDefs
{
    private final MyInterface instance;

    @Inject
    public MyStepDefs(MyInterface instance)
    {
        this.instance = instance
    }
}

I think I need to configure the GuiceFactory using a cucumber-guice.properties file but I don't really know what this is? At the moment the error I get is,

java.lang.NoClassDefFoundError: javax/inject/Singleton
    at cucumber.runtime.java.guice.GuiceFactory$CucumberModule.configure(GuiceFactory.java:86)

Also should I be using a Provider for constructor injection?


Solution

  • The MyModule and MyStepDefs classes were fine. The NoClassDefFoundError was caused by not having latest version of Guice added as a dependency. I added this,

    <dependency>
      <groupId>com.google.inject</groupId>
      <artifactId>guice</artifactId>
      <version>3.0</version>
    </dependency>
    

    to my POM.xml.

    The cucumber-guice.properties file goes in the src/main/resources folder. This file is read by the GuiceFactory class and should contain a property for the Guice module you want to use. EG..

    guiceModule=com.felix.cucumber.MyModule