Skip to content

Instantly share code, notes, and snippets.

@pgoodwin
Created July 9, 2014 22:23
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 pgoodwin/421d80af783087f6848f to your computer and use it in GitHub Desktop.
Save pgoodwin/421d80af783087f6848f to your computer and use it in GitHub Desktop.
An extension of RobolectricTestRunner that overrides a binding in the test module. The runner specializes a TestLifecycle which prepares the injector with the new module.
package com.pivotallabs.post_followers.test_util;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.util.Modules;
import com.pivotallabs.post_followers.api.PostFollowersService;
import com.pivotallabs.post_followers.injection.PostFollowersModule;
import com.pivotallabs.post_followers.injection.PostFollowersTestModule;
import org.junit.runners.model.InitializationError;
import org.robolectric.DefaultTestLifecycle;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.TestLifecycle;
import roboguice.RoboGuice;
import static org.mockito.Mockito.mock;
public class MockApiServiceTestRunner extends RobolectricTestRunner {
public MockApiServiceTestRunner(Class<?> testClass) throws InitializationError {
super(testClass);
}
@Override
protected Class<? extends TestLifecycle> getTestLifecycleClass() {
return MockApiServerTestLifecycle.class;
}
public static class MockApiServerTestLifecycle extends DefaultTestLifecycle {
@Override
public void prepareTest(Object test) {
Injector injector = RoboGuice.setBaseApplicationInjector(
Robolectric.application,
RoboGuice.DEFAULT_STAGE,
RoboGuice.newDefaultRoboModule(Robolectric.application),
Modules.override(new PostFollowersModule())
.with(new PostFollowersTestModule(), new MockApiServerTestModule()));
injector.injectMembers(test);
}
}
public static class MockApiServerTestModule extends AbstractModule {
@Override
protected void configure() {
bind(PostFollowersService.class).toInstance(mock(PostFollowersService.class));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment