2013-08-02 42 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

相关问题