Created
October 13, 2014 19:56
-
-
Save kevints/a6694384c7a72ac3dfef to your computer and use it in GitHub Desktop.
requireBinding is a DRY violation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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