首页 > 解决方案 > @BeforeSuite 和 @AfterSuite 必须是静态的吗?

问题描述

我看到了很多例子,在每个例子中我都没有看到任何关于 testNG 中 beforeSuite 和 afterSuite 中需要的静态

我的情况是我有 MainRunner 和 BaseTest 扩展 MainRunner

主赛跑者:

public static void main(String[] args) {
    TestListenerAdapter tla = new TestListenerAdapter();
    TestNG testng = new TestNG();
    testng.setTestClasses(new Class[] { testRunner.class });
    testng.addListener(tla);
    testng.run();
}

 public class baseTest {
static WebDriver driver;
public static mainPage main;
public static culturePage mainCulturePage;
public static mainArticle mainArticle;

基础测试:

@BeforeSuite
public static void setup() {
   //locating the driver and maximize the browser window
      System.setProperty("webdriver.chrome.driver" , "F:\\java-projects\\.AB-Settings Folder\\chromedriver.exe");
      driver= new ChromeDriver();
      driver.manage().window().maximize();

      //create reporting folder and report
      //init();


      main = new mainPage(driver);
      mainCulturePage = new culturePage(driver);
      mainArticle = new mainArticle(driver);

}


@AfterSuite
public static void close() {
    //extent.flush(); 
    driver.quit();
}

}

所以问题是为什么我需要使它成为静态的?(类和注释)为了让它们运行?除了这些静态之外,它在实例之外工作并且不需要实例的解释是什么?

还有哪些选项可以更改已弃用:

testng.addListener(tla);

标签: javaeclipsetestng

解决方案


您可以使用多级继承来使您的代码更加结构化和易于维护,并且您可以在不使用任何静态方法的情况下做到这一点。
例如:

public class ClassA {

public void setUp() {
    // Perform the setup operation of the driver here
}

public void closeDriver() {
    // Close the driver here
    }
 }

public class ClassB extends ClassA{

@BeforeSuite
public void initializeDriver(){
    //Call the setUp method from ClassA here
    setUp();
}

@AfterSuite
public void closeDriver(){
    //Call the closeDriver method from ClassA here
    closeDriver();
    }

//Add all the other BeforeClass and AfterClass also in this class .    

}

public class ClassC extends ClassB{

@Test
public void testMethod(){
    // Write your test method here
  }

}

因此,通过使用上述多级继承,您不需要将任何方法设置为静态,并且每当您的 @Test 启动时,它将自动运行 ClassB 方法,这些方法将执行脚本的初始化和关闭驱动程序部分。

并且要回答您已弃用的部分问题,当您知道该方法现在已弃用时,您可以在该方法之前使用 @Deprecated 注释,以便将来不再使用该方法。

如果有帮助请告诉我!!


推荐阅读