Way to use system properties with annotation in Selenium? - java

Is there any chance to use annotatios with system properties in Selenium?
#Test
public void
testSigninMobile()
{
if(System.getProperty("browser").equals("iphone")){
login();
}else{
driver.quit();
}
}
I would like to have annotations like that:
#Test if broswer is iphone, firefox but not if it is IE or Edge etc.
public void
testSigninMobile()
{...
I mean the situation where you have for instance 50 tests but your app is not full ready for every browser. I think that it is silly to write to those 50 test such a browser checking logic?

You can write logics inside the #Test method using Capabilities - getBrowserName().
#Test
public void testSigninMobile()
{
Capabilities cap = ((RemoteWebDriver) driver).getCapabilities();
String browserName = cap.getBrowserName().toLowerCase();
System.out.println(browserName);
if("blabla".equalsIgnoreCase(browserName))
{
// Your code
}
else
{
throw new SkipException("Skipping this excecution");
}
}

Related

How to run two test methods in two different browser in parallel using TestNG?

I have one test case contains two methods. When trying the two test methods in two browser instance, only one browser instance can open the website but the rest of the steps can't execute. Another browser instance can't even open the website (blank page).
I've tried the suggested solution on Stackoverflow. Those solutions do not work in my case.
public class RunSimpleTest{
private String baseUrl = "https://mywebsite";
public WebDriver driver;
GlobalFunctions objGlobalFunc;
#BeforeMethod(alwaysRun = true)
public void setup() {
try{
// declaration and instantiation of objects/variables
System.setProperty("webdriver.chrome.driver", "C:/ChromeDriver/chromedriver.exe");
// Disable Chrome Developer Mode Extension
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-extensions");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
objGlobalFunc = new GlobalFunctions(driver);
driver.get(baseUrl);
objGlobalFunc = new GlobalFunctions(driver);
objGlobalFunc.selectEnglishLanguage();
}
catch (Exception e){
e.printStackTrace();
}
}
#Test
public void BTRun1() {
objGlobalFunc.setUserNameValue("ABC");
objGlobalFunc.clickOKBtnOnMEXLoginForm();
}
#Test
public void BTRun2() {
objGlobalFunc.setUserNameValue("ABC");
objGlobalFunc.clickOKBtnOnMEXLoginForm();
}
}
BTRun1 is opened in a chrome browser. And, the user can login.
BTRun2 is opened in another chrome browser. And, the user can login.
The core problem of your code is the usage of global WebDriver object.
When running in parallel, TestNG is creating just one instance of RunSimpleTest, therefore one instance of WebDriver object. That's causing the two test override each other when communicating with the WebDriver object.
One solution would be using ThreadLocalDriver and ThreadLocalGlobalFunctions:
protected ThreadLocalDriver threadLocalDriver;
protected ThreadLocalGlobalFunctions threadLocalGlobalFunctions;
public void setup() {
try{
// declaration and instantiation of objects/variables
System.setProperty("webdriver.chrome.driver", "C:/ChromeDriver/chromedriver.exe");
// Disable Chrome Developer Mode Extension
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-extensions");
options.addArguments("--start-maximized");
threadLocalDriver = new ThreadLocalDriver(options);
threadLocalDriver.getDriver().manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
objGlobalFunc = new ThreadLocalGlobalFunctions(threadLocalDriver.getDriver());
threadLocalDriver.getDriver().get(baseUrl);
objGlobalFunc.getGlobalFunc().selectEnglishLanguage();
}
catch (Exception e){
e.printStackTrace();
}
}
#Test
public void BTRun1() {
objGlobalFunc.getGlobalFunc().setUserNameValue("ABC");
objGlobalFunc.getGlobalFunc().clickOKBtnOnMEXLoginForm();
}
#Test
public void BTRun2() {
objGlobalFunc.getGlobalFunc().setUserNameValue("ABC");
objGlobalFunc.getGlobalFunc().clickOKBtnOnMEXLoginForm();
}
To learn more about using ThreadLocal with WebDriver, check: http://seleniumautomationhelper.blogspot.com/2014/02/initializing-webdriver-object-as-thread.html

How to quit the page if i type hello world on google search using selenium?

Hi guys I want to quit the page afte I type "Hello World" in google search using firefox browser and selenium
WebDriver driver = null;
public static void main(String args[]) {
SimpleSelenium ss = new SimpleSelenium();
ss.openBrowser();
ss.getPage();
ss.quitPage();
}
private void openBrowser() {
System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");
driver = new FirefoxDriver();
}
private void quitPage() {
driver.quit();
}
private void getPage() {
driver.get("http://www.google.com");
}
1) Create a Junit test class
2) Initialize the driver in your setup method like
ChromeDriver driver = new ChromeDriver();//Download chromeDriver.exe file and point to location where you have installed the like as you mentioned. `driver.System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");`
3) Create a test method with your business logic to type hello world
3) Create After and Before Class annotations for the methods .In After class annotation method you can write driver.quit.
You can refer to following link for more clarity
https://www.guru99.com/selenium-tutorial.html
I am Added sample format which is written Using java and testNG..Here Every time First before method will run then 1st test case will execute then after method will work then again before method work then next test case......In this way you can manage your test case and it will also generate Report also.Here you will get better explanation.
public class GoogleTest {
FirefoxDriver driver;
#BeforeMethod
public void setUp1() throws Exception {
System.setProperty("webdriver.gecko.driver", "D:\\\\ToolsQA\\trunk\\Library\\drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void GoogleInputField() throws InterruptedException {
System.out.println("Hello world");
System.out.println("Hello world");
//Write Your test case for test case 1
}
#Test
public void google suggestion() throws InterruptedException {
//Write Your test case for test case 1
}
#AfterMethod
public void getResult(ITestResult result) throws IOException {
driver.quit();
}
}
Dont forget to add Firefox driver on gecko.driver path
I am assuming that you want to open the browser using selenium, load google and then listen till you MANUALLY enter "hello world" in the input box. The method listenForHelloWorld() will do that.
public static void main(String args[]) {
SimpleSelenium ss = new SimpleSelenium();
ss.openBrowser();
ss.getPage();
ss.listenForHelloWorld();
ss.quitPage();
}
private void listenForHelloWorld() {
// Get the search field
WebElement searchField = driver.findElement(By.name("q"));
int count = 1;
while (count++ < 20) {
// if search field value is "hellwo world" break loop which will eventallu lead to `quit()` as it is the next method to exit.
if (searchField.getAttribute("value").equalsIgnoreCase("hello world")) {
break;
}
Thread.sleep(5000)
}
}
If you are asking how to enter "hello world" in browser automatically use below.
driver.findElement(By.name("q")).sendKeys("hello world");

Running Parameterized test seems to hold because of a browser lock?

I am running some tests against multiple browsers, in this case Chrome and Firefox.
It seems thought that after Chrome finishes the tests, Firefox will hang until I force close Chrome's browser window. Then The firefox tests will run.
What could be doing this, and how can i prevent it?
Below is the code I have:
#RunWith(Parameterized.class)
public class MyFirstTest {
private String _platform;
private WebDriver _driver;
private String url = "http://localhost:8000/web/";
private String descSelector = "todo-form paper-input input";
public MyFirstTest(String platform, WebDriver driver){
_platform = platform;
_driver = driver;
}
#Parameterized.Parameters
public static Collection testList(){
return Arrays.asList(new Object[][] {
{"chrome", new ChromeDriver(DesiredCapabilities.chrome())},
{"firefox", new FirefoxDriver(DesiredCapabilities.firefox())}
});
}
#Test
public void testAddToDo() {
_driver.navigate().to(url);
WebEleemnet ele = _driver.findElements(By.cssSelector(descSelector)).get(0);
}
}
It seems to hang up on the navigate call. I think there is something wrong with the scope, but im not really sure what the issue is. The way this is running, i thought it would be async and would not affect each other.
Currently Running: Selenuim 3.0.0beta3, Firefox 49.0.1

Selenium webdriver Page Object Pattern and ExtentReports

Someone could tell me how to write a functional application tests which combine Selenium Page Object Pattern and ExtentsReports (http://extentreports.relevantcodes.com/) to generate reports from these test cases. How to design test class? because I know that validation should be separated from page objects. What is the best approach to do this?
A sample piece of code would be very helpful
It is a good approach, of course, to separate your model (Page Objects) from you tests. For this to happen, you may use a layer of services, i.e. helper classes, which can interact both with business objects and page objects.
Note: I'm going to answer the second part of your question, not that on yet-another lib for reporting.
So, you have a business object:
public class Something {
boolean toHappen;
public Something(boolean toHappen) {
this.toHappen = toHappen;
}
public boolean isToHappen() {
return toHappen;
}
}
You also have your page:
public class ApplicationPage {
// how driver object is put here is your own business.
private static WebDriver driver;
#FindBy(id = "id")
private Button triggerButton;
public ApplicationPage() {
PageFactory.initElements(driver, this);
}
public static ApplicationPage open(){
driver.get("http://page.net");
return new ApplicationPage();
}
public void trigger() {
triggerButton.click();
}
}
So in order not to mix business objects and pages in tests, you create a service:
public class InevitableService {
public static void makeHappen() {
// just a very stupid code here to show interaction
Something smth = new Something(true);
ApplicationPage page = ApplicationPage.open();
if(smth.toHappen()){
page.trigger();
}
}
}
And finally your test
public class TestClass extends Assert {
#Test
public void test() {
InevitableService.makeHappen();
assertTrue(true);
}
}
As a result:
you have no driver in tests
you have no page objects in tests
you operate only high-level logic
Pros:
very flexible
Cons:
gets complicated over time
Considering your reporting tool - I believe it just listens the result of you tests and sends them to server. Or it just takes the xml/html results of you tests and makes pretty and useless pie-charts. Again, has nothing to do with POP.
Steps:
1. Declare variables under Test Suite class
public ExtentReports extent ;
public ExtentTest test;
2. Create object for Extent Managers User defined class
extent = ExtentManager.instance();
3. Pass extent parameter to the Page Object Class
inbound = new DemoPageObject(driver,extent);
4. Goto page object class method and Start with "Start log"
test = extent.startTest("View details", "Unable to view details");
5. For Success steps and we need end test
test.log(LogStatus.PASS, "The list of details are successfully displaying");
test.log(LogStatus.INFO, test.addScreenCapture(ExtentManager.CaptureScreen(driver, "./Send")));
log.info("The list of details are successfully displaying ");
extent.endTest(test);
6. For Failure and no need to end test
test.log(LogStatus.FAIL, "A Technical error is displaying under ");
7. Use #AfterMethod to handle error test cases
#AfterMethod
public void tearDown(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
test.log(LogStatus.FAIL, "<pre>" + result.getThrowable().getMessage() + "</pre>");
extent.endTest(test);
}
}
8. Finally Adding results to the report
#AfterTest
public void when_I_Close_Browser() {
extent.flush();
}
public class ExtentManager {
public static ExtentReports instance() {
ExtentReports extent;
String Path = "./ExtentReport.html";
System.out.println(Path);
extent = new ExtentReports(Path, true);
//extent.config() .documentTitle("Automation Report").reportName("Regression");
extent
.addSystemInfo("Host Name", "Anshoo")
.addSystemInfo("Environment", "QA");
return extent;
}
public static String CaptureScreen(WebDriver driver, String ImagesPath) {
TakesScreenshot oScn = (TakesScreenshot) driver;
File oScnShot = oScn.getScreenshotAs(OutputType.FILE);
File oDest = new File(ImagesPath + ".jpg");
try {
FileUtils.copyFile(oScnShot, oDest);
} catch (IOException e) {
System.out.println(e.getMessage());
}
return ImagesPath + ".jpg";
}
}

Set a firefoxWebDriver.get(...) timeout

i like to access some pages that are not under my control. It could be that this pages execute some slow get requests but the main html is fully loaded and displayed. I tried many options but i could make it. The firefoxWebDriver.get(...) doesn't terminate on some sites in a realistic time.
To reproduice the problem, I wrote this small UnitTest showing the problem:
public class Timeout {
private FirefoxDriver driver;
#Before
public void setup() {
final FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("dom.max_script_run_time", 0);
profile.setPreference("webdriver.load.strategy", "fast");
this.driver = new FirefoxDriver(profile);
// this.driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
// this.driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
}
#Test(timeout = 15000)
public void shouldRetriveREDCAFEPageQuiteFast() {
this.driver.get("http://redcafe.vn/Home/su-kien-binh-luan/kagawa-tu-choi-mac-ao-so-7");
}
#Test(timeout = 15000)
public void shouldRetriveMUFCPageQuiteFast() {
this.driver.get("http://news.mufc.vn/detail/172-hoan-tat-giay-phep-lao-dong-m-u-chinh-thuc-so-huu-kagawa.html");
}
#After
public void tearDown() {
this.driver.close();
}
}
Thanks for you help.
<driver>.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
will set the page load timeout to 60 seconds, after which it will throw an error. You need to set this up before your first get() call.
The API is supported from Webdriver release 2.20.0 onwards.
Refer API Reference for new Timeout API's

Categories

Resources