TestNG之Factory

如果我们的测试方法中,同一个变量需要很多个不同的测试数据,那么这些测试数据由谁提供呢,testng提供了factory的注解,下面我们来一探究竟。

一、单独使用Factory

1.新建一个含有@Factory的类,且在该类中实例化测试类的对象,如

package com.testng;

import org.testng.annotations.Factory;

/** 
 * @author QiaoJiafei 
 * @version 创建时间:2015年12月22日 下午6:17:06 
 * 类说明 
 */
public class TestFactory {

     @Factory
     public Object[] createInstances() {
         Object[] result = new Object[10]; 
         for (int i = 0; i < 10; i++) {
         result[i] = new WebTest(i * 10);
         }
         return result;
      }
        
}

2.新建测试类,并使用这个工厂类提供的数据

package com.testng;

import org.testng.annotations.Test;

/** 
 * @author QiaoJiafei 
 * @version 创建时间:2015年12月22日 下午6:19:10 
 * 类说明 
 */
public class WebTest {
      private int m_numberOfTimes;
      public WebTest(int numberOfTimes) {
        m_numberOfTimes = numberOfTimes;
      }
     
      @Test
      public void testServer() {
       // access the web page
       System.out.println(m_numberOfTimes ); 
  }
}

3.在xml文件中只需要,增加<class name="com.testng.TestFactory"/>即可,注意不需要在xml中在额外定义<class name="com.testng.WebTest"/>。

4.执行结果,打印:

30
10
0
80
70
60
20
40
50
90

5.执行后,报告显示如下:

相当于运行了10次测试方法。The factory method can receive parameters just like @Test and @Before/After and it must return Object[].  The objects returned can be of any class (not necessarily the same class as the factory class) and they don't even need to contain TestNG annotations (in which case they will be ignored by TestNG).

二、Factory和dataProvider 配合使用

package com.testng;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;

/** 
 * @author QiaoJiafei 
 * @version 创建时间:2015年12月22日 下午6:17:06 
 * 类说明 
 */
public class TestFactory {

     /*@Factory
     public Object[] createInstances() {
         Object[] result = new Object[10]; 
         for (int i = 0; i < 10; i++) {
             result[i] = new WebTest(i * 10);
         }
         return result;
      }*/
     @Factory(dataProvider = "dp")
     public Object[] createInstances(int n) {
         Object[] result = new Object[1];
         for (int i = 0; i < 1; i++) {
             result[i] = new WebTest(n);
         }
         return result;
     }
      
     @DataProvider
     static public Object[][] dp() {
       return new Object[][] {
         new Object[] { 41 },
         new Object[] { 42 },
       };
     }

        
}

执行结果,打印:

41

42

报告显示执行了两次测试方法

posted on 2015-12-22 18:50  乔叶叶  阅读(659)  评论(0编辑  收藏  举报

导航