Skip to content
Advertisement

TestNG assign programatically DataProvider

If I have a method:

JavaScript

Can I create a Listener or something in TestNG, that if I have a method:

JavaScript

then it automatically injects specific dataProvider, without explicitly specifying it @Test(dataProvider = "webTarget") ?

Advertisement

Answer

Ideally speaking, the easiest way to go about doing this would be to:

  1. Define an abstract class in which you define the required data provider and also the data that your data provider would feed off of, as its source and give it to the test methods (It could be something like the data provider feeds off of an injected value into it)
  2. Have your test classes, extend this abstract class and then from within an org.testng.IAnnotationTransformer implementation, you merely inject the data provider method name into the test class.

In case you don’t want to use an abstract class also, then here’s another alternative. This kind of looks like a round about way of doing it.

For this example, the dependency injection framework that I am using is Guice.

The interfaces that we are going to be using in this example are as below

JavaScript
JavaScript

Here’s how the Guice module that we are using in this example looks like

JavaScript

Here’s how the test class looks like

JavaScript

Here’s how the separate data provider class would look like

JavaScript

The annotation transformer looks like below:

JavaScript

The data provider listener looks like below:

JavaScript

Here’s how the suite xml would look like

JavaScript

Here’s the chain of events that are expected to happen:

  1. The test class uses a Guice Module which injects the required dependencies into the test class.
  2. The test class exposes the injected dependency to any caller (data provider listener in this case) via the interface com.rationaleemotions.dynamic.ObjectGetter
  3. We have an implementation of org.testng.IAnnotationTransformer using which we inject a data provider class and a method reference into the test method.
  4. The data provider class is a separate class that implements com.rationaleemotions.dynamic.ObjectSetter using which it would get hold of the data it should use for data driven tests.
  5. We create an implementation of org.testng.IDataProviderListener which TestNG provides to eavesdrop into before and after invocation events for data providers. Using this listener we extract out the Guice injected data from the test class and then inject it back into the object to which the data provider belongs to.

This is a bit long way of doing this, but goes a bit more to making the data providers truly dynamic.

Your mileage on using is likely to vary depending upon the actual use case in which you would like to employ such a “sophisticated but yet convoluted approach”.

Advertisement