2013-08-02 81 views
1

嗨,我是Webdriver和Junit的新手。需要解決這個難題。我做了很多研究,但找不到可以幫助的人。Junit/Webdriver - 爲什麼我的瀏覽器正在啓動兩次

因此,我宣佈我的驅動程序最高爲靜態Webdriver fd,然後嘗試運行單個類文件(也嘗試多個類文件)的情況下,但每次運行瀏覽器啓動兩次。我似乎可以調試這個問題,請幫助。這裏是我的代碼:

package Wspace; 

import java.io.IOException; 
import java.util.concurrent.TimeUnit; 

import junit.framework.Assert; 

import org.junit.Before; 
import org.junit.Rule; 
import org.junit.Test; 
import org.junit.rules.ErrorCollector; 

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.openqa.selenium.firefox.FirefoxProfile; 
import org.openqa.selenium.firefox.internal.ProfilesIni; 

public class Wsinventory { 

    static WebDriver fd; 

    @Rule 
    public static ErrorCollector errCollector = new ErrorCollector(); 

    @Before 
    public void openFirefox() throws IOException 
    {   
     System.out.println("Launching WebSpace 9.0 in FireFox"); 

     ProfilesIni pr = new ProfilesIni(); 
     FirefoxProfile fp = pr.getProfile("ERS_Profile"); //FF profile 

     fd = new FirefoxDriver(fp); 
     fd.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 

     fd.get("http://www.testsite.com"); 
     fd.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); 

     String ffpagetitle = fd.getTitle(); //ffpagetitle means firefox page title 
     //System.out.println(pagetitle); 
     try{ 
     Assert.assertEquals("Webspace Login Page", ffpagetitle); 
     }catch(Throwable t){ 
      System.out.println("ERROR ENCOUNTERED"); 
      errCollector.addError(t); 
     } 

    }  

    @Test 
    public void wsloginTest(){ 

     fd.findElement(By.name("User ID")).sendKeys("CA"); 
     fd.findElement(By.name("Password")).sendKeys("SONIKA"); 
     fd.findElement(By.name("Logon WebSpace")).click(); 
    } 

    @Test 
    public void switchtoInventory() throws InterruptedException{ 

     Thread.sleep(5000); 
     fd.switchTo().frame("body"); //Main frame 
     fd.switchTo().frame("leftNav"); //Sub frame 
     fd.findElement(By.name("Inventory")).click(); 
     fd.switchTo().defaultContent(); 
     fd.switchTo().frame("body"); 
    } 


} 

回答

2

問題是,你的@Before方法是在每次測試之前運行。當你運行你的第二個測試時,它會再次調用該方法,並丟棄舊的FirefoxDriver實例,並創建一個新的實例(存儲在該驅動程序的靜態實例中)。

改爲使用@BeforeClass

+0

謝謝MrTi ...它的工作......一個問題,但如果一個類有@BeforeClass爲什麼junit要求我有一個測試方法也是一樣的?它不斷給我初始化錯誤。我想在單獨的課程中編寫我的測試。 – user2646842

+0

我不明白你在說什麼。要麼谷歌錯誤,或者提出另一個問題:P快樂自動化。 –

+0

謝謝MrTi ..你很高興花時間回答我的問題。我想問的是。我想在獨立的課程文件中編寫我的'測試'。所以我編寫了一個基類文件,我在其中定義了BaseClass anotation和一個Driver實例(用於我的所有測試)。但是junit要求我在Base類文件中添加一個@Test。我通過提供一個空白的測試方法來完成。但是當我運行我的套件時,這個空白測試方法與我所有的其他測試一起運行。造成問題。需要知道哪種方法更好,即在單獨的類文件中編寫測試或在一個文件中進行所有測試? – user2646842

相關問題