Skip to content

Instantly share code, notes, and snippets.

@mgenov
Created July 16, 2013 13:59
Show Gist options
  • Save mgenov/6008948 to your computer and use it in GitHub Desktop.
Save mgenov/6008948 to your computer and use it in GitHub Desktop.
Sample test which compares factory vs provider
import com.google.inject.Provider;
import com.google.inject.util.Providers;
import org.jmock.Expectations;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
/**
* @author Miroslav Genov ([email protected])
*/
public class SampleTest {
public interface AnotherObject {
void doSomething();
}
public interface Factory {
AnotherObject create();
}
class FactoryObject {
private final Factory factory;
public FactoryObject(Factory factory) {
this.factory = factory;
}
public void methodUnderTest() {
AnotherObject o = factory.create();
o.doSomething();
}
}
class ProviderObject {
private final Provider<AnotherObject> anotherObjectProvider;
public ProviderObject(Provider<AnotherObject> anotherObjectProvider) {
this.anotherObjectProvider = anotherObjectProvider;
}
public void methodUnderTest() {
AnotherObject o = anotherObjectProvider.get();
o.doSomething();
}
}
@Rule
public JUnitRuleMockery context = new JUnitRuleMockery();
AnotherObject anotherObject;
Factory factory;
@Before
public void initialize() {
anotherObject = context.mock(AnotherObject.class);
factory = context.mock(Factory.class);
}
@Test
public void providerSample() {
ProviderObject p1 = new ProviderObject(Providers.of(anotherObject));
context.checking(new Expectations() {{
oneOf(anotherObject).doSomething();
}});
p1.methodUnderTest();
}
@Test
public void factorySample() {
FactoryObject p1 = new FactoryObject(factory);
context.checking(new Expectations() {{
oneOf(factory).create();
will(returnValue(anotherObject));
oneOf(anotherObject).doSomething();
}});
p1.methodUnderTest();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment