Guice Module Testing (made harder than it should have been?)
George Malamidis, March 13th, 2007I have a question stemming from my first – and very hasty mind you – impressions of Google Guice:
If testing is one of the major benefits achieved by using the proposed style of programming, what’s the deal with the Fluent Interface used to bind assets:
public void configure(Binder binder) {
binder.bind(Service.class).to(NothingService.class);
}
Sure it looks funky, but to test the code above you need not one, but 2 mocks.
public void testShouldBindService() {
Mock binder = mock(Binder.class);
Mock annotatedBindingBuilder = mock(AnnotatedBindingBuilder.class);
annotatedBindingBuilder.expects(once()).method("to")
.with(eq(NothingService.class));
binder.expects(once()).method("bind")
.with(eq(Service.class))
.will(returnValue(annotatedBindingBuilder.proxy()));
new MyModule().configure((Binder) binder.proxy());
}
Phew… Half of this test code could have been avoided if the com.google.inject.Module API had a less clever bind(Key<Object> key, Class<? extends T> value) method on it…

March 13th, 2007 at 2:59 pm
I’m very curious about this. Do you see a lot of value in testing your Module class itself? In our app we unit-test our implementation classes (no Injector involved), we have some small “layer tests” (for lack of a better term) which construct custom simple Injectors so as to test a handful of classes working in concert, and then we have functional tests of our whole application using the production Injector. It would have never occurred to us to try to write a test for the Module itself; we’d see that as time that could have been spent testing something more likely to break.
March 13th, 2007 at 3:00 pm
man, lately I am really determined that my blog be a “.org” … very strange.