有人可以解释一下为什么@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"));
}
}
当我直接在@Test(到最后)部分从@After移动代码时,我的项目成功关闭了浏览器。项目汇编良好。
答案 0 :(得分:1)
在您的示例代码中,您有两个不同的driver
变量。一个是startWeb
方法的本地方法,用于创建浏览器实例。另一个变量是在类级别,并且从不实例化。这是您尝试在ShutdownWeb
方法中使用的实例。要解决此问题,请不要在setup方法中重新声明本地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
的建议是合理的,我在上面的代码中包含了这一更改。
答案 1 :(得分:0)
而不是使用@之前你可以试试......
@BeforeClass
baseUrl = "http://localhost:8080/";
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get(baseUrl);
and @AfterClass
driver.quit();
所以尝试使用它对我有用。
答案 2 :(得分: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"));
}
}
试试这.....它的作品