-1

有人可以解释一下为什么@After 部分中的方法在测试后不关闭浏览器吗?

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 部分(到最后)时,我的项目成功关闭了浏览器。项目编译好。

4

3 回答 3

1

在您的示例代码中,您有两个不同的driver变量。一个是startWeb方法本地的,用于创建您的浏览器实例。另一个变量在类级别,并且永远不会被实例化。这是您尝试在ShutdownWeb方法中使用的实例。要解决此问题,请不要driver在 setup 方法中重新声明局部变量。以机智:

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是合理的,我在上面的代码中包含了该更改。

于 2013-07-30T23:42:05.133 回答
0

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

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

and @AfterClass
  driver.quit();

所以尝试使用它对我有用。

于 2013-07-30T17:50:57.913 回答
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"));

    }
}

试试这个.....它的工作原理

于 2013-07-31T04:46:55.727 回答