Thursday, June 4, 2015

TestNG Using @Factory and @DataProvider

Combination of data providers and factory annotations in TestNg can be used to reiterate the same test class with different test data. This will enable users to use the same class seamlessly without duplicating the test class code. Lets look at what each annotation does and real usage of it.

@Factory -  Can be used to execute all the test methods present inside a test class, using separate instance of the same class.  That means running the class in parametrized way by providing different inputs to class constructor.

@DataProvider - A test method that uses DataProvider will be executed a multiple number of times based on the data provided by the DataProvider. The test method will be executed using the same instance of the test class to which the test method belongs.

Below code segment will illustrate usage of @Factory with @DataProvider annotation.


Execution result of the class as follows. You can see that 8 test methods have been executed with different user mode parameters. 
 
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running TestSuite
Before Running the class userMode is Admin
Inside method 1 Admin
Inside method 2 Admin
Before Running the class userMode is Tenant
Inside method 1 Tenant
Inside method 2 Tenant
Before Running the class userMode is AdminUser
Inside method 1 AdminUser
Inside method 2 AdminUser
Before Running the class userMode is TenantUser
Inside method 1 TenantUser
Inside method 2 TenantUser
Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.625 sec

Results :

Tests run: 8, Failures: 0, Errors: 0, Skipped: 0

5 comments:

Unknown said...

Before Running the class userMode is Tenant
Inside method 1 Tenant
Before Running the class userMode is TenantUser
Inside method 1 TenantUser
Before Running the class userMode is Admin
Inside method 1 Admin
Before Running the class userMode is AdminUser
Inside method 1 AdminUser
Inside method 2 Tenant
Inside method 2 TenantUser
Inside method 2 Admin
Inside method 2 AdminUser

Unknown said...

Hi Krishana,

I executed the same program But got Output in below format

Before Running the class userMode is Tenant
Inside method 1 Tenant
Before Running the class userMode is TenantUser
Inside method 1 TenantUser
Before Running the class userMode is Admin
Inside method 1 Admin
Before Running the class userMode is AdminUser
Inside method 1 AdminUser
Inside method 2 Tenant
Inside method 2 TenantUser
Inside method 2 Admin
Inside method 2 AdminUser

Krishantha Samaraweera said...

Hi Sachin,

How you execute the tests. Is it though your IDE ?

Unknown said...

I got the same above results. Executed it in Eclipse IDE. Its not giving the results you mentioned.

Krishantha Samaraweera said...

@Anil - Can you run the maven pom file and see.. whether it gives the same result.