Trying to close the browser when a test fails in Selenium. Tried to include an AfterMethod but not browser is still not closing on fail. Any help would be greatly appreciated!
Here is my java class:
public class googleTestClass extends Methods{
public void executeGoogle() throws InterruptedException {
this.goToURL("https://www.google.com");
this.enterValue("name","q","google test 1");
}
@Test
public void test1() throws InterruptedException {
googleTestClass object1;
object1 = new googleTestClass();
object1.launchBrowser();
object1.executeGoogle();
}
@Test
public void test2() throws InterruptedException {
googleTestClass object2;
object2 = new googleTestClass();
object2.launchBrowser();
object2.executeGoogle();
}
@AfterMethod
public void tearDown() throws InterruptedException, IOException {
driver.quit();
}
}
Here is the mentioned Methods class: // import statements
public class Methods {
public WebDriver driver;
public void launchBrowser() {System.setProperty("webdriver.chrome.driver","C:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
}
public void goToURL(String url) {
driver.get(url);
}
public void enterValue(String htmltype, String identifier, String value) throws InterruptedException {
if (htmltype == "id") {
WebElement element = driver.findElement(By.id(identifier));
element.clear();
element.sendKeys(value);
element.submit();
}
if (htmltype =="name") {
WebElement element = driver.findElement(By.name(identifier));
element.clear();
element.sendKeys(value);
element.submit();
}
Thread.sleep(3000);
}
Here is the used testNG file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="methods">
<test thread-count="5" name="Test" parallel="methods">
<classes>
<class name="webDrivertests.googleTestClass">
<methods>
<include name ="test1"/>
<include name ="test2"/>
</methods>
</class>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Is the AfterMethod
not being reached because it is written incorrectly or does the problem lies in driver.quit?
Any help would be great. Thank you!
答案 0 :(得分:0)
问题在于,当您运行Test类并调用@AfterMethod
时,它正试图从属于顶级类而不是方法内部实例化的类的驱动程序中退出。这是一个更好理解的小示例:
JUnit测试类:
import org.junit.Test;
import org.junit.After;
public class intTestClass extends Methods{
@Test
public void test1() throws InterruptedException {
intTestClass object1;
object1 = new intTestClass();
object1.setInt();
}
@After
public void tearDown() {
System.out.println("testInt is: "+ testInt);
}
}
和Methods类:
public class Methods {
public int testInt = 0;
public void setInt() {
testInt = 1;
}
}
在这里,当您运行JUnit测试时,您期望的是将testInt
的值打印为1。但是,带有注释@After(@AfterMethod for testng)
的方法将检查{{1 }}变量属于顶级 intTestClass,而不是在testInt
方法中实例化的 intTestClass 。
因此,我们看到的输出为:
test1()
如果我们将此应用于您的方案,则需要做的是将testInt is: 0
方法移入测试类中,并使用launchBrowser()
批注调用该方法。