Thursday, February 5, 2015

Netflix Governator Tests - Introducing governator-junit-runner

Consider a typical Netflix Governator junit test.

public class SampleWithGovernatorJunitSupportTest {

    public LifecycleTester tester = new LifecycleTester();

    public void testExampleBeanInjection() throws Exception {
        Injector injector = tester
                .withBootstrapModule(new SampleBootstrapModule())

        BlogService blogService = injector.getInstance(BlogService.class);
        assertThat(blogService.get(1l), is(notNullValue()));
        assertThat(blogService.getBlogServiceName(), equalTo("Test Blog Service"));


This test is leveraging the Junit rule support provided by Netflix Governator and tests some of the feature sets of Governator - Bootstrap modules, package scanning, configuration support etc.

The test however has quite a lot of boilerplate code which I felt could be reduced by instead leveraging a Junit Runner type model. As a proof of this concept, I am introducing the unimaginatively named project - governator-junit-runner, consider now the same test re-written using this library:

@LifecycleInjectorParams(modules = SampleModule.class, bootstrapModule = SampleBootstrapModule.class, scannedPackages = "")
public class SampleGovernatorRunnerTest {

    private BlogService blogService;

    public void testExampleBeanInjection() throws Exception {
        assertEquals("Test Blog Service", blogService.getBlogServiceName());


Most of the boilerplate is now implemented within the Junit runner and the parameters required to bootstrap Governator is passed in through the LifecycleInjectorParams annotation. The test instance itself is a bound component and thus can be injected into, this way the instances which need to be tested can be injected into the test itself and asserted on. If you want more fine-grained control, the LifecycleManager itself can be injected into the test!:

private Injector injector;

private LifecycleManager lifecycleManager;

If this interests you, more samples are at the project site here.

No comments:

Post a Comment