-1

有人可以解釋我爲什麼在@節中的方法在測試後沒有關閉瀏覽器?爲什麼我不能通過webdriver關閉瀏覽器?

package TestCases; 

import junit.framework.Assert; 
import org.junit.After; 
import org.junit.Before; 
import org.junit.Test; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.ie.InternetExplorerDriver; 

public class ScriptCase { 

    private WebDriver driver; 

    @Before 
    public void startWeb() { 
     WebDriver driver = new InternetExplorerDriver(); 

     driver.navigate().to("https://play.google.com/store/apps/details?id=com.recursify.pixstack.free&hl=en"); 
    } 

    @After 
    public void ShutdownWeb() { 
     driver.close(); 
    } 

    @Test 
    public void startWebDriver(){ 

     Assert.assertTrue("Title is different from expected", 
       driver.getTitle().startsWith("PixStack Photo Editor Free")); 

    } 
} 

當我從@After直接移動代碼@Test(到最後)我的項目成功關閉瀏覽器。項目編譯好。

+0

試試這個代替'driver.browser.close' –

+0

2馬丁拉爾森: 我已經得到了提示:無法解析符號 '瀏覽器' – Vyacheslav

+0

驅動程序。 quit()關閉所有webdriver實例 –

回答

0

而不是使用@之前你可以試試...

 @BeforeClass 
    baseUrl = "http://localhost:8080/"; 
    driver = new FirefoxDriver(); 
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); 
    driver.get(baseUrl); 

and @AfterClass 
    driver.quit(); 

因此,嘗試使用這個工作對我來說。

+0

Grate,它解決了我的問題! – Vyacheslav

1

在您的示例代碼中,您有兩個不同的driver變量。其中一個是startWeb方法的本地方法,用於創建瀏覽器實例。另一個變量處於類級別,並且從不實例化。這是您嘗試在您的ShutdownWeb方法中使用的實例。要解決此問題,請不要在您的設置方法中重新聲明本地driver變量。即:

public class ScriptCase { 

    private WebDriver driver; 

    @Before 
    public void startWeb() { 
    // This is the line of code that has changed. By removing 
    // the type "WebDriver", the statement changes from declaring 
    // a new local-scope variable to use of the already declared 
    // class scope variable of the same name. 
    driver = new InternetExplorerDriver(); 
    driver.navigate().to("https://play.google.com/store/apps/details?id=com.recursify.pixstack.free&hl=en"); 
    } 

    @After 
    public void shutdownWeb() { 
    driver.quit(); 
    } 

    @Test 
    public void startWebDriver(){ 

    Assert.assertTrue("Title is different from expected", driver.getTitle().startsWith("PixStack Photo Editor Free")); 

    } 
} 

此外,建議使用quit方法,而不是close是聲音,我已經包含在上面我的代碼變化。

+0

謝謝你,你是對的!我聲明瞭變量兩次。 – Vyacheslav

0
public class ScriptCase { 

    private WebDriver driver; 

    @BeforeClass 
    public void startWeb() { 
     driver = new InternetExplorerDriver(); 
     driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); 
     driver.navigate().to("https://play.google.com/store/apps/details?id=com.recursify.pixstack.free&hl=en"); 
    } 

    @AfterClass 
    public void ShutdownWeb() { 
     driver.close(); 
     driver.quit(); 
    } 

    @Test 
    public void startWebDriver(){ 

     Assert.assertTrue("Title is different from expected", 
       driver.getTitle().startsWith("PixStack Photo Editor Free")); 

    } 
} 

試試這個.....它的工作原理

相關問題