Reputation: 2475
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?
Upvotes: 3
Views: 8851
Reputation: 369
As of cucumber-guice v1.2.4 this has changed slightly. Firstly the configuration file has changed its name, and it is now cucumber.properties
.
Secondly, now in addition to building the module, you have to build a class which extends cucumber.runtime.java.guice.InjectorSource
and set that as the value of guice.injector-source
in the properties file. So in addition to the two classes you've already created you'd have to create a third:
public class MyInjectorSource implements InjectorSource {
@Override
public Injector getInjector() {
return Guice.createInjector(Stage.PRODUCTION, CucumberModules.createScenarioModule(), new MyModule());
}
}
then in cucumber.properties
set guice.injector-source to the fully qualified name of this new class. cucumber.properties
should, as before, be in src/main/resources
(or src/test/resources
depending on your requirements).
Naturally you still need the dependency in your pom.xml
file.
Upvotes: 5
Reputation: 2475
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
Upvotes: 2