How do i configure selenium with a remote phantomjs drive in junit? I have been trying to find a tutorial for this but had no luck. My goal is to use this for testing in spring mvc for my single page application.
After some trial and error I have reached the following solution. This configuration is used in the Junit test class
private URI siteBase;
private static PhantomJSDriverService service;
private WebDriver driver;
protected static DesiredCapabilities dCaps;
#BeforeClass
public static void createAndStartService() throws IOException {
service = new PhantomJSDriverService.Builder().usingPhantomJSExecutable(new File("/path/to/phantom/driver"))
.usingAnyFreePort()
.build();
service.start();
}
#AfterClass
public static void stopService() throws IOException {
service.stop();
}
#Before
public void setUp() throws Exception {
siteBase = new URI("http://localhost:8080/");
dCaps = new DesiredCapabilities();
dCaps.setJavascriptEnabled(true);
dCaps.setCapability("takesScreenshot", false);
driver = new RemoteWebDriver(service.getUrl(),dCaps);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#After
public void tearDown() throws Exception {
driver.quit();
}
If you need further information comment below.
Related
Webdriver: close web driver only if test is successful.
Is there a way to check test results in #After method?
public class FooTest {
private WebDriver webDriver;
#Test
public void testFoo() {
}
#After
public void cleanUp() {
if (isTestSuccess()) { // How?
webDriver.close();
}
}
}
If you are using Junit, you can pass the Scenario parameter to the tear down method:
#After
public void cleanUp(Scenario scenario) {
if (!scenario.isFailed()) {
webDriver.close();
}
}
public class One {
public WebDriver driver;
#Test
public void test1() {
/*System.setProperty("webdriver.chrome.driver", "Y:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();*/
driver.findElement(By.id("username")).sendKeys("abc#ccp.com");
driver.findElement(By.id("password")).sendKeys("password!1");
System.out.println("im in first test case from demoTwo Class");
}
#BeforeMethod
public void test() {
System.setProperty("webdriver.chrome.driver", "Y:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://app.anywebsite.com");
System.out.println("im in first test case from demoONE Class");
}
#AfterMethod
public void afterMethod() {
// Close the driver
driver.quit();
}
}
How do I pass the driver object to subsequent test methods?
Sample code available for testng on web shows this kind of structure but none executes.
You just set your driver by this way:
#BeforeMethod
public void test() {
System.setProperty("webdriver.chrome.driver", "Y:\\chromedriver.exe");
this.driver = new ChromeDriver();
driver.get("https://app.anywebsite.com");
System.out.println("im in first test case from demoONE Class");
}
i been working on the selenium driver which i have to close the new tab else the current Testcase will fail due unable to allocate the directory of xpath. I notice that im calling 3 times of the webdriver , can anyone guide me through the mistake i made? Kindly advise . Thanks you in advance
SignIn_Action:
public class SignIn_ActionBuilder {
static WebDriver wd = new FirefoxDriver();
public static void Execute(WebDriver driver) throws Exception{
wd.get(Constant.URL);
wd.manage().window().maximize();
wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
Home_Page.Skip_Advertising(wd).click();
Home_Page.lnk_MyAccount(wd).click();
LogIn_Page.txtbx_UserName(wd).sendKeys(Constant.Username);
LogIn_Page.txtbx_Password(wd).sendKeys(Constant.Password);
wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
LogIn_Page.btn_LogIn(wd).click();
wd.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
}
}
Product Selection :
public class ProductSelectionConfirmation_Action {
static WebDriver wd = new FirefoxDriver();
public static void ThreeDigit_Execute(WebDriver driver) throws Exception{
// This is to get the Product name on the Confirmation page with using getText()/click method
// Once some text is stored in this variable can be used later in any other class
wd.manage().wait(120);
wd.close();
ConfirmationPlaceBet_Page.pick_PickLotteryNum1(wd).click();
ConfirmationPlaceBet_Page.pick_PickLotteryNum2(wd).click();
ConfirmationPlaceBet_Page.pick_PickLotteryNum3(wd).click();
ConfirmationPlaceBet_Page.btn_ConfirmNumberToBet(wd).click();
for (int i = 0; i < 49; i++) {
ConfirmationPlaceBet_Page.btn_IncreaseBet(wd).click();
}
ConfirmationPlaceBet_Page.btn_ProceedBet(wd).click();
ConfirmationPlaceBet_Page.btn_ConfirmBet(wd).click();
// This is all about Verification checks, these does not stop your execution but simply report fail at the end
// This is to check that if the value in the variable pick_PickLotteryNum1 is not null, then do this
}
}
TestCase :
public class Sobet_WBG_YiWanCai {
public WebDriver driver;
#Test(description = "WBG亿万彩 - 后三码" , enabled = true)
public void f() throws Exception {
try{
SignIn_ActionBuilder.Execute(driver);
ProductSelectionConfirmation_Action.ThreeDigit_Execute(driver);
Home_Page.lnk_LogOut(driver);
Home_Page.btn_LogOutDialog(driver);
driver.close();
}catch (Exception e){
Log.error(e.getMessage());
throw (e);
}
}
}
I can see a series of issues with the code you have posted.
In each of the Action classes you are creating a new static web driver object.
static WebDriver wd = new FirefoxDriver();
Which means it will open a new Firefox browser when the class is called.
And also you are passing a webdriver object in to the execute methods from the test case. But the passed webdriver is never used in the execute methods.
public static void ThreeDigit_Execute(WebDriver driver) throws Exception{}
You are not using the driver object for any action in the method but uses the wd object throughout the method.
Corrected code for the first class execute method :
public class SignIn_ActionBuilder {
public static void Execute(WebDriver driver) throws Exception{
driver.get(Constant.URL);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
Home_Page.Skip_Advertising(driver).click();
Home_Page.lnk_MyAccount(driver).click();
LogIn_Page.txtbx_UserName(driver).sendKeys(Constant.Username);
LogIn_Page.txtbx_Password(driver).sendKeys(Constant.Password);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
LogIn_Page.btn_LogIn(driver).click();
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
}
}
And from the test case you have to create a webdriver object and pass it into the execute methods.
public class Sobet_WBG_YiWanCai {
public WebDriver driver;
#Test(description = "WBG亿万彩 - 后三码" , enabled = true)
public void f() throws Exception {
try{
//Create the driver instance here.
driver = new FirefoxDriver();
SignIn_ActionBuilder.Execute(driver);
ProductSelectionConfirmation_Action.ThreeDigit_Execute(driver);
Home_Page.lnk_LogOut(driver);
Home_Page.btn_LogOutDialog(driver);
driver.close();
}catch (Exception e){
Log.error(e.getMessage());
throw (e);
}
}
}
And you have to remove the static WebDriver wd = new FirefoxDriver(); line from all your action classes.
I'm running into a strange JUnit and Selenium issue.
I want to write a screenshot taker that will take a screenshot on failed tests.
I define the screenshot taker class as:
public class SeleniumJUnitScreenshotTaker implements MethodRule
{
private WebDriver driverLocal;
public SeleniumJUnitScreenshotTaker(WebDriver driver)
{
driverLocal = driver;
}
public void takeScreenshot(String fileName)
{
try
{
new File("test-results/scrshots/").mkdirs(); // Make sure directory is there
FileOutputStream out = new FileOutputStream("test-results/scrshots/" + fileName + ".png");
out.write(((TakesScreenshot) driverLocal).getScreenshotAs(OutputType.BYTES));
out.close();
}
catch (Exception e)
{
// No need to crash the tests here
}
}
public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o)
{
return new Statement()
{
#Override
public void evaluate() throws Throwable
{
try
{
statement.evaluate();
}
catch (Throwable t)
{
takeScreenshot(frameworkMethod.getName());
throw t; // rethrow
}
}
};
}
I've a base test class where I setup the WebDriver as follows:
public class TestBase
{
protected static WebDriver driver;
#Rule
public SeleniumJUnitScreenshotTaker seleniumJUnitScreenshotTaker = new SeleniumJUnitScreenshotTaker(driver);
.
.
.
#BeforeClass
public static void intialize()
{
.
.
driver = SeleniumWebDriverFactory.getWebDriver(browser.toString());
if ((browser != Browser.Chrome) && (browser != Browser.ChromeCanary))
{
driver.manage().window().maximize();
}
hostUrl = Configuration.getHostUrl(envUnderTest);
// Open Browser and navigate to main page
driver.navigate().to(hostUrl);
}
#Before
protected void setup() throws Exception
{
this.users = getUsers();
}
#After
protected void teardown()
{
this.testCases.cleanupChecks();
}
#AfterClass
public static void terminate()
{
// Shut down WebDriver
if (driver != null)
driver.quit();
SeleniumWebDriverFactory.stopDriverService();
}
}
The problem is when I try to run a series of tests in the test class (derived from TestBase), the tests after the first failure throws TimeoutException. This is because we don't close the current browser between tests and the new test tries to find things that are absent in current browser.
Is there a way to close browser in between tests but not close the driver? Or reinstantiate the driver between tests? Else is there an alt. design that can make this work?
Thanks
Yana
#BeforeClass does not start my tests in Webdriver, Java, and I don't know where do I go wrong
#BeforeClass
public static void setup() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(baseUrl + "login");
driver.findElement(By.id("username")).sendKeys("myUserName");
driver.findElement(By.id("password")).sendKeys("myPassword");
driver.findElement(By.id("loginBTN")).click();
}
After the code I start the regular testing:
#Test
public void firstTest() {
//myTestCode
}
After attempting to run, all tests fail, the webdriver does not start, etc...
It would be nice to have this since I have to test a page where I have to be logged in (with #Before the webdriver starts before each test, so obviously I would need the #BeforeClass for this one.)
#BeforeClass
public static void setup() {
//This needs to be here for this to run and having this here means its only local to this method
Webdriver driver;
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(baseUrl + "login");
driver.findElement(By.id("username")).sendKeys("myUserName");
driver.findElement(By.id("password")).sendKeys("myPassword");
driver.findElement(By.id("loginBTN")).click();
}
Then your Test will work
#Test
public void firstTest() {
//myTestCode
}
Sample Code : Hopes this will work.
public class OpenBrowsers {
WebDriver driver = null;
#BeforeClass
public void beforeClass() {
System.out.println("beforeClass");
driver = new FirefoxDriver();
}
#Test
public void openGoogle() {
System.out.println("openGoogle");
driver.get("www.google.com");
}
#Test
public void openYahoo() {
System.out.println("openYahoo");
driver.get("www.yahoo.com");
}
#AfterClass
public void afterClass() {
driver.close();
System.out.println("afterClass");
}}