Reputation: 49
How can I open and close the browser after each test case execution in Selenium?
Scenario: let's suppose there is a main class file, say "TestCases.JAVA", contains several test case methods and I want to open the browser at the beginning of each test case and then close browser after its execution.
Currently, I am getting the following error:
org.openqa.selenium.SessionNotCreatedException: Tried to run command without establishing a connection
The demo test cases design is like this...
public class TC_Login {
@Test(priority=1)
public static void TC_VerifyPageTitle_1() {
TestBaseSetup.OpenBrowser();
String actual=TestBaseSetup.driver.getTitle();
String expected= "Google";
Assert.assertEquals(actual, expected);
test.log(LogStatus.INFO, "Starting verify Title test");
test.log(LogStatus.INFO, "Ending verify Title test");
test.log(LogStatus.PASS, "Title verified");
TestBaseSetup.closeBrowser();
}
@Test(priority=2)
public static void TC_Login_2() {
TestBaseSetup.OpenBrowser();
String actual=TestBaseSetup.driver.getTitle();
String expected= "Google";
Assert.assertEquals(actual, expected);
test.log(LogStatus.INFO, "Starting verify Title test");
test.log(LogStatus.INFO, "Ending verify Title test");
test.log(LogStatus.PASS, "Title verified");
Action.Wait(3);
Re_Login.signIn();
TestBaseSetup.closeBrowser();
// test.log(LogStatus.INFO, "Browser closed");
}
}
I have searched on Google, but I have not found any useful information.
Upvotes: 0
Views: 3043
Reputation: 4739
You have to use BeforeMethod
and AfterMethod
Annotations,in this example first launchBrowser()
is called then URLcall1()
then closeBrowser()
, second time launchBrowser()
is called then URLcall2()
then closeBrowser()
Please find below code:
public class Stackoverflow_demo {
WebDriver d=null;
@BeforeMethod
public void launchBrowser()
{
d =new FirefoxDriver();
}
@Test(priority=1)
public void URLcall1()
{
d.get("https://google.co.in");
}
@Test(priority=2)
public void URLcall2()
{
d.get("https://stackoverflow.com");
}
@AfterMethod
public void closeBrowser()
{
d.close();
}
}
Upvotes: 0