【问题标题】:How can I pass a string from one method to another using TestNG?如何使用 TestNG 将字符串从一种方法传递到另一种方法?
【发布时间】:2016-01-14 19:59:24
【问题描述】:

在我的测试中,我将在一种方法中捕获一个字符串,然后在另一种方法中使用它。这是我正在尝试做的一个示例:

public class stackOverflowExample {

public static WebDriver driver;
public static Properties OR = null;

@Test
public void test_1() throws InterruptedException {

System.setProperty("webdriver.ie.driver","D:\\iedriver\\IEDriverServer.exe");               
driver=new InternetExplorerDriver();


 driver.get("http://www.google.com");

Thread.sleep(1500);

String string1 = driver.findElement(By.id("btnK")).getText();

System.out.println(string1);

}

public void test_2() {

  System.out.println(string1);


}
}

如何在 test_2() 方法中使用 string1?

*编辑:

为了弄清楚我为什么要这样做,我正在运行一个执行以下操作的测试:

  1. 以User1登录网站
  2. 创建新的抵押贷款申请
  3. 退出 User1,然后在 User2 下重新登录
  4. 然后用户 2 将打开新创建的抵押贷款应用程序并运行各种测试场景。

【问题讨论】:

  • 在课堂上全球化?
  • 对于我在这方面的知识有限,我深表歉意。我对此很陌生。我将如何使其全球化?

标签: java selenium automation testng


【解决方案1】:

你想要它:

public class SomeTest {

    public static String string1 = null; // It's a global String

    @Test
    public void test1() {
        string1 = "blabla"; // Change value for global String
        System.out.println(string1); // Print value of global String
    }

    @Test
    public void test2() {
        System.out.println(string1); // Print value of global String
    }

}

【讨论】:

    【解决方案2】:

    从技术上讲,不鼓励您尝试做的事情。单元测试应该独立于每个测试。

    同样,执行测试时没有严格的顺序。我的意思是,test_2() 实际上可以在 test_1() 之前进行测试,因此 string1 无论如何都不能用于 test_2()。测试也可以并行运行。

    正确的做法是,IMO 也是在 test_2() 中进行获取 string1 的调用...如果您认为类中的每个测试都需要获取 string1 这一步,请考虑使用 @Before 注释对于 setup(),它是一个在所有测试之前执行并将 string1 存储在类级别变量中的函数。

    希望这会有所帮助。

    【讨论】:

    • 对不起,我急着写这个例子。我通常有一个“主”方法来运行不同的方法以便编写它们。例如,Master 方法会说: public void master() { test_1(); test_2(); }
    猜你喜欢
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多