之前在测试中一直使用testNG的@Test注解都很顺利没有碰到什么问题,今天突然遇到@Test不能用的情况,运行后提示:

org.testng.TestNGException:

Can't invoke public void testautomation.debugAssertion.testdebug(): either make it static or add a no-args constructor to your class

赶紧查看测试类是不是什么地方写的不对,函数调用关系是不是写对了,检查后代码并没有问题,于是上网查资料后恍然大悟,是因为测试类没有被实例化导致@Test的方法不能正常调用。以前没碰到问题是因为测试类没有定义有参构造函数。

分析后发现:

在run as TestNG test的时候,TestNG会调用测试用例所在测试类的无参构造方法,从而将测试类实例化,然后执行在每个类中的测试方法。但是我的测试类只有一个有参构造函数,TestNG不能实例化类。

于是继续找解决办法,发现@Factory只会被调用一次,而且@Factory方法优先于@Test方法和配置方法被调用,只有当所有的@Factory方法被调用之后,TestNG才执行@Test方法和配置方法。

既然TestNG无法实例化对象,那么我们就用@Factory来帮它完成这个任务。

代码也比较简单,如下:

         @Factory
public static Object[] create() throws IOException{
List<debugAssertion> result = new ArrayList<debugAssertion>();
Assertion as = new Assertion();
result.add(new debugAssertion(as));
return result.toArray();

将这个方法加入到测试类中后运行run as TestNG test,运行成功!!!

[TestNG] Running:
C:\Users\IBM_ADMIN\AppData\Local\Temp\testng-eclipse-1577888796\testng-customsuite.xml 2017-03-16 11:14:19 testautomation.Assertion : verify success : 1
Thread-1 : true
[]
PASSED: testdebug on Thread[Thread-0,5,main] ===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
=============================================== ===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
05-21 16:54