I started using Guice to do dependency injection in the project, primarily because I need to embed the mocks (using JMock currently) layer from unit test, which makes manual injection very inconvenient.
My question is, what is the best approach for introducing a layout? I currently have a new module in unit test that satisfies the dependencies and binds them to a provider that looks like this:
public class JMockProvider<T> implements Provider<T> { private T mock; public JMockProvider(T mock) { this.mock = mock; } public T get() { return mock; } }
Passing the layout in the constructor, so the JMock setup might look like this:
final CommunicationQueue queue = context.mock(CommunicationQueue.class); final TransactionRollBack trans = context.mock(TransactionRollBack.class); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(CommunicationQueue.class).toProvider(new JMockProvider<QuickBooksCommunicationQueue>(queue)); bind(TransactionRollBack.class).toProvider(new JMockProvider<TransactionRollBack>(trans)); } }); context.checking(new Expectations() {{ oneOf(queue).retrieve(with(any(int.class))); will(returnValue(null)); never(trans); }}); injector.getInstance(RunResponse.class).processResponseImpl(-1);
Is there a better way? I know that AtUnit is trying to solve this problem, although I miss how it automatically introduces a layout created locally, as mentioned above, but I am looking for either a convincing reason why AtUnit is the correct answer here (other than its ability to change DI and bullying framework without changing the tests), or if there is a better solution for this manually.
java guice jmock
Yishai
source share