+ 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

| numberOfBeans |
| 4 |
| 2 |

Dagger Setup

Start by defining your Dagger 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 {

Belly belly;

public DirtiesContextBellyStepDefs() {

@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());
class StepDef {
private static CucumberComponent INSTANCE = null;

static CucumberComponent getInstance() {
if (INSTANCE == null) {
INSTANCE = DaggerCucumberComponent.builder()
return INSTANCE;
public DirtiesContextBellyStepDefs() {


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