I just started learning Google Guice and developed a first example from
Guice git-hub.
My code looks something like this
example.
My scenario to which I have a question:
In the Guice-example the BillingService calls a CreditCardProcessor#charge(creditCard, amount).
The credit card and amount is set to the CreditCardProcessor.
My GuiceBillingService gets the CreditCardProcessor via injection and sets the credit card to it through #chargeOrder() of my BillingService.
My test case looks like this:
@Override
public void setUp() throws Exception {
injector = Guice.createInjector(new FakeBillingModule());
}
@Override
public void tearDown() throws Exception {
injector = null;
}
public void testSuccessfulCharge() {
BillingService billingService = injector.getInstance(BillingService.class);
Receipt receipt = billingService.chargeOrder(order, creditCard);
assertTrue(receipt.hasSuccessfulCharge());
assertEquals(16.8, receipt.getAmountOfCharge());
FakeCreditCardProcessor processor = (FakeCreditCardProcessor) injector.getInstance(CreditCardProcessor.class);
assertEquals(creditCard, processor.getCardOfOnlyCharge());
assertEquals(16.8, processor.getAmountOfOnlyCharge());
InMemoryTransactionLog transactionLog = (InMemoryTransactionLog) injector.getInstance(TransactionLog.class);
assertTrue(transactionLog.wasSuccessLogged());
}
Currently my module-configuration binds the CreditCardProcessor in scope SINGLETON:
@Override
protected void configure() {
bind(TransactionLog.class).to(InMemoryTransactionLog.class).in(Scopes.SINGLETON);
bind(CreditCardProcessor.class).to(FakeCreditCardProcessor.class).in(Scopes.SINGLETON);
bind(BillingService.class).to(GuiceBillingService.class);
}
So if not SINGLETON then a new CreditCardProcessor is created and assertEquals(creditCard, processor.getCardOfOnlyCharge()); will fail.
If my module does not configure the processor in scope SINGLETON Guice creates a new object via injector.getInstance() - so far so good, but how it's possible to get the same CreditCardProcessor from BillingService from Guice instead of using getters from the BillingService-instance?
How can I get the same instance of CreditCardProcessor that has been changed within the BillingService?
If scope SINGLETON is used the scope applies to application what means that it's always the same instance when I run tests in parallel?
Whats the preferred way to get injected dependencies from a Guice-created-instance? Are getters a recommended solution? I thought - if I use a DI-framework it should be able to get all concrete instances from it instead...?!
Thanks for some advice and help!
-Danny