I’m preparing a presentation of Guice, where I plan to demonstrate the (correct) behaviour of Guice by executing Unit Tests. In the following test case, I want to ensure that the correct types were injected
@Test
public void shouldInjectCorrectDependencies() {
Injector injector = Guice.createInjector(new ModuleImpl());
House house = injector.getInstance(House.class);
Assert.assertTrue(house.door().getClass() == (WoodenDoor.class));
}
Now, I wonder which approach would be better:
- Using getClass() to check for a concrete class
- Using instanceof to check for a type (and subtypes)
I no expert on Guice, but in Spring DI, you can have instances injected which are not instances of the class you’re expecting. For instance, in your example, if
Houseis not a class, but an interface, then spring under certain circumstances (for instance if you’re using a transaction) gives you a Proxy, not an instance of a class which implements the interface. The only guarantee you have is that it will implement the correct interface. So I would use: