且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TestNG方法测试及注意要点 代码及配置详解(解决testng方法不执行问题)

更新时间:2022-08-17 08:34:45

教你解决为什么TestNG中方法加了@Test注解,也在配置文件中配置了,但是方法就是不执行!


在使用TestNG进行测试时,使用配置文件的方式更容易于维护,但是经常遇到明明方法写了也配置执行了,但是run的时候代码就没有执行

看代码:(仔细看注释!)

/**
 * 
 * <p>
 * Title: TestngMethods
 * </p>
 * 
 * <p>
 * 对应配置文件testng-methods.xml
 * Description: Testng的methods测试及配置,参考testng-methods.xml,如果不设置
 * exclude和include,默认执行当前测试类时,带有返回值的方法不会被执行
 * 
 * 如果想执行多个同类型或者命名方式类似的多个方法时,可以使用方法组测试,
 * '.*'表示一个或多个字符,如果方法命名方式不同,那么可以采用组测试方法进行测试,参考TestGroups
 * 
 * 注:文档错误!
 * 
 * 5.1 - Test methods Test methods are annotated with @Test. Methods annotated
 * with @Test that happen to return a value will be ignored, unless you set
 * allow-return-values to true in your testng.xml:
 * 
 * <suite allow-return-values="true">
 * 
 * or
 * 
 * <test allow-return-values="true">
 * 
 * 此处在<test >中配置allow-return-values属性无效,测试依旧不会被执行
 * </p>
 * 
 * <p>
 * Company:
 * </p>
 * 
 * @author : Dragon
 * 
 * @date : 2014年10月11日
 */
public class TestngMethods {
	/**
	 * 默认情况下这个方法将被忽略,如果需要执行,需要在xml中配置allow-return-values="true"
	 * 
	 * @return
	 */
	@Test
	public String getName() {
		System.err.println("return name.... getName()");
		return "name";
	}

	@Test
	public void funtest() {
		System.err.println("this is funtest......");
	}

	@Test
	public void saveMethod1() {
		System.err.println("this is saveMethod1......");
	}

	@Test
	public void saveMethod2() {
		System.err.println("this is saveMethod2......");
	}

	@Test
	public void saveMethod3() {
		System.err.println("this is saveMethod3......");
	}

}

配置文件:testng-methods.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<!-- allow-return-values 默认值为FALSE,表示返回值将被忽略 -->
<suite name="framework_testng" allow-return-values="true">
	<test verbose="2" name="TestMethods">
		<classes>
			<class name="com.dragon.testng.annotation.TestngMethods">
				<methods>
					<exclude name="funtest"></exclude>
					<include name="getName"></include>
					<include name="save.*"></include>
				</methods>
			</class>
		</classes>
	</test>
</suite>


运行结果:

return name.... getName()
this is saveMethod1......
this is saveMethod2......
this is saveMethod3......
PASSED: getName
PASSED: saveMethod1
PASSED: saveMethod2
PASSED: saveMethod3

===============================================
    TestMethods
    Tests run: 4, Failures: 0, Skips: 0
===============================================


Testng 的数据源 驱动测试 代码与配置



如果我忍让,
别认为我退缩。因为我明白,忍一忍风平浪静,让一让天高海阔。