2016-01-14 54 views
0

在我的測試中,我要在一種方法中捕獲一個字符串,然後以不同的方法使用它。以下是我正在嘗試執行的一個示例:如何使用TestNG將字符串從一種方法傳遞給另一種方法?

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. 登錄到網站的用戶1
  2. 下創建一個新的抵押貸款應用程序
  3. 註銷用戶1,然後重新登錄到用戶2下
  4. 然後,用戶2將打開新創建的抵押貸款應用程序並運行各種測試場景。
+0

使它成爲全球上課? – amkz

+0

我對這方面有限的知識表示歉意。我對此很新。我將如何去使其成爲全球? –

回答

0

你想要的:

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 
    } 

} 
0

從技術上講,你試圖做的是不鼓勵。單元測試意味着獨立於每個測試。

另外afaik,測試執行時沒有嚴格的順序。我的意思是,test_2()實際上可以在test_1()之前進行測試,因此string1對test_2()無效。測試也可以並行運行。

要做到這一點,IMO的正確方法是在test_2()中進行調用以獲取string1 ...如果您認爲獲取string1的這一步對於類中的每個測試都是必需的,請考慮使用@Before setup()的註釋,它是在所有測試之前執行的函數,並將string1存儲在類級變量中。

希望這會有所幫助。

+0

對不起,我急着寫這個例子。我通常有一個「主」方法來運行不同的方法來編寫它們。例如,主方法會說: public void master(){ test_1(); test_2(); } –

相關問題