TestNG中@BeforeGroups方法未执行问题求助
问题描述
我编写了如下TestNG测试代码:
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class NewTest { @BeforeTest private void beforeTest() { System.out.println("BeforeTest!"); } @BeforeGroups(groups = "demo") private void initialize() { System.out.println("BeforeGroups!"); } @Test(groups = { "demo" }) private void test() { System.out.println("Test!"); } }
运行该测试类后,控制台仅输出"BeforeTest!"和"Test!",标记@BeforeGroups的initialize方法未被调用。
运行日志如下:
[RemoteTestNG] detected TestNG version 7.4.0 BeforeTest! Test! PASSED: test =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 =============================================== =============================================== Default suite Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 ===============================================
请问这是什么原因?
原因分析及解决方案
问题出在initialize方法的访问修饰符上:你给这个方法设置了private权限,TestNG无法通过反射调用私有方法,所以@BeforeGroups注解没有生效。
TestNG要求所有带有注解的测试方法(包括@BeforeGroups、@Test、@BeforeTest等注解标记的方法)必须是非私有的,也就是可以使用public、protected或者默认包访问权限(不写修饰符)。
修改后的代码示例:
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class NewTest { @BeforeTest public void beforeTest() { // 建议统一改为public,避免后续潜在问题 System.out.println("BeforeTest!"); } @BeforeGroups(groups = "demo") public void initialize() { // 改为public System.out.println("BeforeGroups!"); } @Test(groups = { "demo" }) public void test() { // 改为public System.out.println("Test!"); } }
修改后重新运行,initialize方法就会被正常调用,控制台会依次输出"BeforeTest!"、"BeforeGroups!"和"Test!"。
内容的提问来源于stack exchange,提问作者Robert Ilin
相关产品推荐
相关产品推荐

