Difference between @Factory and @DataProvider annotations

Both the annotations belong to TestNg testing framework. Many people get confused while reading about these two annotations that why and where we have to use these two?

Very basic difference between these two are-

@DataProvider- DataProvider annotations parameterize the particular test method and execute the test number of times based on data provided by DataProvider method. So if two parameters are there then test will execute twice.

@Factory- Factory executes all the test methods present inside any test class file using separate instance of the respective class.

Still confused???

Let’s have look on some programs-

@DataProvider
public Object[][] message(){
return new Object [][]{{“Mayank” , new Integer (321)}, {“Dileep”, new Integer (282)}};
}

@Test (dataProvider=”message”)
public void PrintMsg(String name, Integer id){
System.out.println(“Names are: “+name+” “+id);
}

As above program states that there are two data and if I run this program result will be-

Result1

So, it proves that if you increase the number of data in message method, PrintMsg method will execute same number of times.

Now we will see Factory and how it is different from DataProvider-

public class TestFactory {
@Factory
public Object[] factorymethod(){
return new Object[]{new DPandFactoryExaple(), new DPandFactoryExaple()};
}}

public class DPandFactoryExaple {
@DataProvider
public Object[][] message(){
return new Object [][]{{“Mayank” , new Integer (321)}, {“Dileep”, new Integer (282)}};
}
@Test (dataProvider=”message”)
public void PrintMsg(String name, Integer id){
System.out.println(“Names are: “+name+” “+id);
}
@Test
public void PrintSuccessfullMessage(){
System.out.println(“Print the successfull message”);
}}

So if we see DPandFactoryExaple class then you will find there are two @Test methods and 1 @Test method has to execute twice and 1 @Test method has to execute once. So there should be 3 messages.

Now if you see @Factory method it is calling the same class twice and in that case there should be 6 messages. See the results below-

Result2

So did it clear the doubts?? No, then comment it out we will discuss it.