Factory


Factories allow you to create tests dynamically. For example, imagine you want to create a test method that will access a page on a Web site several times, and you want to invoke it with different values.(means TestNG factory is used to create instances of test classes. This is useful if you want to run the test class any no of times.)

Lets create a java class for basic example for @Factory method

package testngexp;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;

publicclass factoryexp1 {
String msgstr;
public factoryexp1(String strg){
msgstr=strg;
}

@Test
publicvoid fMethod(){
System.out.println(msgstr);
}

@Factory
public Object[] fdata(){
returnnew Object[]{new factoryexp1("This is First Factory example"),new factoryexp1("This is Second Factory example")};
}
}

TestNG.xml file

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEsuiteSYSTEM"http://testng.org/testng-1.0.dtd">
<suitename="Suite"verbose="1">
<testname="Test1">
<classes>
<classname="testngexp.factoryexp1"/>
</classes>
</test><!-- Test -->
</suite><!-- Suite -->

Results

image

Lets see another example for @Factory Method

In Below example we define @Factory method in different way

package testngexp;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;

publicclass factoryexp1 {
String msgstr;
public factoryexp1(String strg){
msgstr=strg;
}

@Test
publicvoid fMethod(){
System.out.println(msgstr);
}

@Factory
public Object[] fdata(){
Object[] res=new Object[2];
res[0]=new factoryexp1("This is First Factory example");
res[1]=new factoryexp1("This is Second Factory example");
return res;
}
}

Lets see another example for @Factory Method
Here @Factory method defined in one class and functionality is another class
Lets create @Factory Method in factExp1 class

package testngexp;
import org.testng.annotations.Factory;

publicclass factExp1 {
@Factory
publicObject[] getdata(){
Object[] data=new Object[2];
data[0]=new factExp2("kiran","testKiran");
data[1]=new factExp2("anitha","testanitha");
return data;
}
}

Lets create another class factExp2

package testngexp;
import org.testng.annotations.Test;

publicclass factExp2 {
String sUsrName,sPWD;
factExp2(String username,String pwd){
sUsrName=username;
sPWD=pwd;
}

@Test
publicvoid TestLoginMethod(){
System.out.println("User Name -->"+sUsrName+" "+"Password--->"+sPWD);
}
}

TestNG.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEsuiteSYSTEM"http://testng.org/testng-1.0.dtd">
<suitename="Suite"verbose="1">
<testname="Test1">
<classes>
<classname="testngexp.factExp1"/>
</classes>
</test><!-- Test -->
</suite><!-- Suite -->


In testng.xml needs to reference the class that contains the factory method, since the test instances themselves will be created at runtime.

<classname="testngexp.factExp1"/>

Results

image

Comments