TestNG @Factory批注

时间:2020-02-23 14:41:56  来源:igfitidea点击:

TestNG @Factory注释用于将方法指定为工厂,以提供TestNG用于测试类的对象。
标有@Factory批注的方法应返回Object数组。

TestNG @Factory批注

当您要通过一个测试类运行多个测试类时,TestNG Factory很有用。
让我们来看一个TestNG Factory注释的快速示例。

假设我们有两个Test类,其中定义了很少的测试方法。

package com.theitroad.utils;

import org.testng.annotations.Test;

public class Test1 {

	@Test
	public void test1() {
		System.out.println("Test1 test method");
	}
}
package com.theitroad.utils;

import org.testng.annotations.Test;

public class Test2 {

	@Test
	public void test2() {
		System.out.println("Test2 test method");
	}
}

现在,我们可以定义一个Factory方法,该方法返回上述类的Object数组。

package com.theitroad.utils;

import org.testng.annotations.Factory;

public class TestNGFactory {

	@Factory()
	public Object[] getTestClasses() {
		Object[] tests = new Object[2];
		tests[0] = new Test1();
		tests[1] = new Test2();
		return tests;
	}
	
}

下图显示了在上面的类中作为TestNG测试类运行的输出。

这是Eclipse控制台中产生的输出。

[RemoteTestNG] detected TestNG version 6.14.3
Test1 test method
Test2 test method
PASSED: test1
PASSED: test2

===============================================
  Default test
  Tests run: 2, Failures: 0, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================

请注意,如果我们进行Maven构建,并且存在更多的TestNG测试类,则它们还将全部执行。
我有另一个TestNG测试类,下面是maven build的输出。

Running TestSuite
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configurator@3224f60b
Test2 test method
Test3 test method
Test1 test method
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.342 sec

Results :

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

因此,如果任何工厂方法都返回了Test类,则默认的测试套件中将排除该类。

我们还可以在同一测试类或者不同测试类中创建多个@Factory方法。

使用DataProvider的TestNG工厂

当我们进行项目构建时,我们所有的测试用例都将被执行。
那么使用Factory方法有什么好处?

好吧,当将它与DataProvider一起使用并且测试类构造函数具有参数时,这将非常有益。

假设我们的" Test1"类定义为:

package com.theitroad.utils;

import org.testng.annotations.Test;

public class Test1 {

	private String str;
	
	public Test1(String s) {
		this.str = s;
	}
	
	@Test
	public void test1() {
		System.out.println("Test1 test method. str = "+str);
	}
}

如果仅将此类作为TestNG测试类运行,则它将为构造函数的字符串参数分配默认值,并产生以下输出。

Test1 test method. str = Default test
PASSED: test1

在这种情况下,我们可以将DataProvider和Factory一起使用,以为构造函数提供输入。

package com.theitroad.utils;

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

public class TestNGFactory {

	@Factory(dataProvider = "dp")
	public Object[] getTestClasses(String s) {
		Object[] tests = new Object[2];
		tests[0] = new Test1(s);
		tests[1] = new Test2();
		return tests;
	}
	
	@DataProvider
	public Object[] dp() {
		return new Object[] {"A", "B"};
	}
}

当我们在测试类之上运行时,它将产生以下输出。

Test1 test method. str = A
Test1 test method. str = B
Test2 test method
Test2 test method
PASSED: test1
PASSED: test1
PASSED: test2
PASSED: test2