Skip to content
This repository has been archived by the owner on May 21, 2019. It is now read-only.
aslakhellesoy edited this page Sep 13, 2010 · 6 revisions

Dependency Injection with Google Guice

If you are using Google Guice in your application, you can get your dependencies injected into your step definitions with the GuiceFactory. Enabling Guice is done with a jvm argument:

-Dcuke4duke.objectFactory=cuke4duke.internal.jvmclass.GuiceFactory

This can be passed via Ant, Maven or the Command Line.

You also have to provide the class name of the Guice configuration module you wish to use. This is also a jvm argument:

-Dcuke4duke.guiceModule=billing.DependenciesModule

All test steps are now injected with Guice. This means that you can use @Inject exactly as you use it in your application.

public class BillingSteps {

    @Inject
    private BillingService billingService;

    private Transaction transaction;

    private CreateTransactionResponse response;

    @Given("^I have a transaction$")
    public void iHaveATransaction() {
        transaction = new Transaction("12345678", new BigDecimal("50.00"));
    }

    @When("^I send the transaction to billing$")
    public void iSendTheTransactionToBilling() {
        response = billingService.sendTransactionToBilling(transaction);
    }

    @Then("^the response should be OK$")
    public void theResponseShouldBeOK() {
        assertTrue(response.isOK());
    }

}

Calling Steps from StepDefinitions

Follow the instructions on Calling Steps from StepDefinitions but remember to add the @Inject annotation to get the StepMother injected to your constructor.

public class CallingSteps extends Steps {
    @Inject
    public CallingSteps(StepMother stepMother) {
        super(stepMother);
    }

    @When("^I call another step$")
    public void iCallAnotherStep() {
        Given("it is magic"); // This will call a step defined somewhere else.
    }
}

Complete Example

Check out the Guice example for a complete example.

Clone this wiki locally