Differences between @Factory and @DataProvider
@Factory and @DataProvider in TestNG
TestNG provides powerful annotations to handle test data and test execution flow efficiently. Two commonly used annotations are @Factory and @DataProvider. Let’s understand them in a simple way.
@Factory Annotation
- @Factory is used to create multiple instances of a test class dynamically.
- It helps in running the same test class with different data sets.
- The method annotated with @Factory returns an array of objects.
- Each object represents a test class instance with different input values.
- Useful when constructor-based injection is required.
@DataProvider Annotation
- @DataProvider is used to supply multiple sets of data to a test method.
- It returns a two-dimensional Object array (Object[][]).
- Each row represents a different test execution.
- Test method receives data as parameters.
- Useful for data-driven testing without creating multiple class instances.
@Factory vs @DataProvider
The differences between @Factory and @DataProvider annotation are as follows:
| @Factory | @DataProvider | |
|---|---|---|
| Purpose | Create multiple instances of test classes | Provide multiple data sets to a test method |
| Return Type | Object[] (array of class instances) | Object[][] (2D array of data) |
| Execution Level | Class level | Method level |
| Data Injection | Via constructor | Via method parameters |
| Use Case | When test class needs different configurations | When same test method runs with multiple data sets |
| Complexity | Slightly complex | Easy to implement |
Conclusion: Use @DataProvider for simple data-driven tests and @Factory when you need more control over test class instantiation.