Search code examples
javatestngguicegovernator

How to inject dependecies using Governator within TestNG test cases?


I'm working on a test automation framework which use TestNG. I decided to use Dependency Injection pattern in order to implement more readable, reusable page objects and tests.

I've chosen Google Guice due to TestNG provides built-in support to inject test objects with Guice Modules. I only had to specify my Guice Modules as you can see at next code snippet:

    @Guice(modules = CommModule.class)
    public class CommunicationTest {

        @Inject
        private Communication comms;

        @Test
        public void testSendMessage() {
            Assertions.assertThat(comms.sendMessage("Hello World!")).isTrue();
        }
    }

So far so good, although I'm going to need more advance DI features such as:

  • Lifecycle management
  • Configuration to field mapping
  • Generic binding annotations

Therefore, I'd like to use Netflix/Governator since it enhance Google Guice with these features. In order to trigger Governator features I must create the Injector through it instead of TestNG. e.g:

    Injector injector = LifecycleInjector.builder()
        .withModules(CommModules.class).build().createInjector();

And I'd like to do it mostly transparent as possible like TestNG does it.

I would like to know if:

  • Is it possible to provide my own Injector instance to TestNG in order to reuse @Guice annotation approach ?
  • Do you know any library for integrating Governator with TestNG ?

You can find in here what I've done so far.


Solution

  • This was not possible until now. I have fixed this in the latest snapshot version of TestNG. It should be available in the upcoming version of TestNG (Any version greater than 7.0.0)

    The issue that I created to track this : https://github.com/cbeust/testng/issues/2199

    In a nutshell, you can do the following :

    • Implement the interface org.testng.IInjectorFactory
    • Plugin the fully qualified class name of the newly created implementation via the command line argument -dependencyinjectorfactory