2013-07-29 82 views
3

我在自動化過程中使用Junit 4和Selenium webdriver。我有多個測試用例,每個測試用例都需要登錄功能。在webdriver中維護瀏覽器會話

我想在同一瀏覽器窗口中運行所有測試用例,並維護登錄會話,而不是爲每個測試用例打開新的瀏覽器,並且每次都進行登錄。 (在我目前的腳本中,我正在每個測試用例中啓動webdriver,並且它會爲每個測試用例打開一個新窗口,並且每次都進行登錄)

我想運行一個測試套件,其中我想運行所有測試個案在同一瀏覽器窗口中。請給我一個解決方案。 代碼:

public class first { 
public static WebDriver driver; 
@BeforeClass 
public static void beforeClass() 
{ 
    System.setProperty("webdriver.chrome.driver", "E:/chromedriver.exe"); 
    System.out.println("Before class"); 
    driver = new ChromeDriver(); 
} 
@Test 
public void login()throws Exception 
{ 
     driver.get("URL"); 
    WebElement login = driver.findElement(By.xpath("my xpath"); 
    login.findElement(By.id("username")).sendKeys("username"); 
    login.findElement(By.id("password")).sendKeys("pwd"); 
    driver.findElement(By.xpath("my xpath")).click(); 
} 

}

創建的第二類:

public class second { 
public static WebDriver driver; 
{ 
@Test 
public void nextstep()throws Exception 
{ 
    WebElement buttons = driver.findElement(By.xpath("my xpath")); 
    buttons.findElement(By.className("Classname")).click(); 

} 

}

測試套件類:

@RunWith(Suite.class) 
@SuiteClasses({first.class, second.class}) 
public class testsuite 
{ 
public static WebDriver driver; 
@BeforeClass 
public static void setUpClass() 
{ 
    System.out.println("Master Setup"); 
} 

} 

回答

0

你需要實現一個套件設置方法打開一個新的瀏覽器窗口並登錄。這樣,在執行所有測試之前,該方法將被調用一次。

要將方法指定爲套件設置方法,請將其置於套件類中,使其成爲靜態並使用@BeforeClass(請參閱this answer中的示例)對其進行註釋。

在您發佈的代碼,在第一類中的driver變量,並在第二類中的driver變量是不一樣的變量。這就是爲什麼在第一類中初始化它會使第二類中的driver初始化並且您得到NullPointerException
如果你想在兩個類中使用相同的變量,你需要定義一個基類,它有一個非靜態變量driver(爲什麼你首先把它設置爲靜態?),然後從基類派生出兩個類類。

+0

好吧,我得到「Null.PointerException」 – user2376425

+0

很遺憾聽到這個,但我不能幫你沒有更多細節。你能發佈產生這個異常的代碼嗎? – Joe

+0

我看到你編輯你的問題來添加代碼。哪一行會拋出'NullPointerException'? – Joe

-1
driver.get("URL"); 
WebElement login = driver.findElement(By.xpath("my xpath"); 

這個代碼,你必須把@Before方法,而不是@Test所以同一會話將繼續