Skip to content

Instantly share code, notes, and snippets.

@kevints
Created October 13, 2014 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevints/a6694384c7a72ac3dfef to your computer and use it in GitHub Desktop.
Save kevints/a6694384c7a72ac3dfef to your computer and use it in GitHub Desktop.
requireBinding is a DRY violation
import javax.inject.Inject;
import javax.inject.Named;
import com.google.inject.AbstractModule;
import com.google.inject.CreationException;
import com.google.inject.Guice;
import com.google.inject.Key;
import com.google.inject.name.Names;
import org.junit.Test;
public class GuiceTest {
static AbstractModule testModule(final boolean require) {
return new AbstractModule() {
@Override
protected void configure() {
if (require) {
requireBinding(Key.get(String.class, Names.named("greeting")));
}
bind(Injected.class);
}
};
}
static AbstractModule stringModule() {
return new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("greeting")).toInstance("hello");
}
};
}
static class Injected {
@Inject @Named("greeting")
private String greeting;
}
@Test
public void testRequiredPresentWithRequireBinding() {
Guice.createInjector(testModule(true), stringModule()).getInstance(Injected.class);
}
@Test(expected = CreationException.class)
public void testRequiredAbsentWithRequireBinding() {
Guice.createInjector(testModule(true)).getInstance(Injected.class);
}
@Test
public void testRequiredPresentWithoutRequireBinding() {
Guice.createInjector(testModule(false), stringModule()).getInstance(Injected.class);
}
@Test(expected = CreationException.class)
public void testRequiredAbsentWithoutRequireBinding() {
Guice.createInjector(testModule(false)).getInstance(Injected.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment