Cucumber.io + Dagger

Photo by Michael Longmire on Unsplash
Feature: Dagger Dirty Cukes
In order to have a completely clean system for each scenario
As a purity activist
I want each dirty scenario to have its own application context

Scenario Outline: Eat some annotated dirty cukes
Given there are 0 dirty cukes in my belly
When I have <numberOfBeans> dirty cukes in my belly
Then there are <numberOfBeans> dirty cukes in my belly

Examples:
| numberOfBeans |
| 4 |
| 2 |

Dagger Setup

Start by defining your Dagger component.

@Component
public interface CucumberComponent {
void inject(DirtiesContextBellyStepDefs stepDefs);
// add an inject method for every step definition
}

Injecting data

Cucumber-jvm requires each of your step definitions include a default constructor (Recall if you don’t specify a constructor the compiler will generate one for your).

public class DirtiesContextBellyStepDefs {

@Inject
Belly belly;

public DirtiesContextBellyStepDefs() {
DaggerCucumberComponent.builder()
.build().inject(this);
}

@Then("there are {int} dirty cukes in my belly")
public void checkCukes(final int n) {
assertEquals(n, belly.getCukes());
}

@Given("I have {int} dirty cukes in my belly")
public void haveCukes(final int n) {
assertEquals(0, belly.getCukes());
belly.setCukes(n);
}
}
class StepDef {
private static CucumberComponent INSTANCE = null;

static CucumberComponent getInstance() {
if (INSTANCE == null) {
INSTANCE = DaggerCucumberComponent.builder()
.build();
}
return INSTANCE;
}
}
public DirtiesContextBellyStepDefs() {
StepDef.getInstance().inject(this);
}

Conclusion

Because Dagger generates dependency injection code at compile time there is no need to utilize special libraries required for other dependency injection frameworks. Instead you must simply explicitly perform your own injections. Borrowing from Python “Explicit is better than implicit”, which applies to Dagger as well.

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store