Responce time for steps (WebDriver + Jmeter) - selenium

I have a test, where I:
Go to the link
Input Login and Password and press Login button
Press Some link
Press LogOut button
I run it in JMeter with 5 users, and I should save some data in csv file, like:
UserName, Login (or smth from 4 steps about), Average time.
In output I should have a file where I can see, that 5 user do step "Login" for average time (5 second for example). How to know average time - find all steps "Login" plus all time and divide on user count (5)?

Implement it in JMeter as follows:
WebDriver Sampler with Label Go to the link
WebDriver Sampler with label Login
WebDriver Sampler with label Navigate
WebDriver Sampler with label Logout
WebDriver code for each sampler should look as follows:
WDS.sampleResult.sampleStart()
// put code for login, navigate, logout, etc.
WDS.sampleResult.sampleEnd()
WebDriver session will remain between samplers and JMeter is smart enough to measure average response times, just add a relevant listener, i.e. Aggregate Report
See The WebDriver Sampler: Your Top 10 Questions Answered guide for more tips and tricks.

No, it's not passed for me, I use JUnit. Here's my code:
public class LoadTestTwo extends TestCase {
private WebDriver driver;
public FirefoxProfile profile = new FirefoxProfile();
public int index=0;
private long start;
private long end;
boolean alreadyExists = new File("C:\\output.csv").exists(); //write estimate time to file
public LoadTestTwo(){
reset();
//start = System.currentTimeMillis();
}
public void end(){
end = System.currentTimeMillis();
}
public long duration(){
return (end-start);
}
public void reset(){
start = 0;
end = 0;
}
public LoadTestTwo(String testName){
super(testName);
}
#Before
public void setUp() throws Exception {
super.setUp();
}
#Test
public void testTestLoad() throws InterruptedException, IOException, FileNotFoundException {
LoadTestTwo t = new LoadTestTwo();
try {
CsvWriter csvOutput = new CsvWriter(new FileWriter("C:\\output.csv",true),',');
if (!alreadyExists) {
csvOutput.write("Users");
csvOutput.write("Steps");
csvOutput.write("Average Time");
csvOutput.endRecord();
}
driver = new FirefoxDriver();
t.reset();
start = System.currentTimeMillis();
driver.get("somelink"); //just hided the real link
t.end();
csvOutput.write("LoadTest2");
csvOutput.write("Go to URL");
csvOutput.write("" + t.duration());
csvOutput.endRecord();
t.reset();
start = System.currentTimeMillis();
start = System.currentTimeMillis();
driver.findElement(By.id("loginForm:authLogin")).sendKeys("User1");
driver.findElement(By.id("loginForm:authPassword")).sendKeys("123456");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.MILLISECONDS);
driver.findElement(By.id("loginForm:btnLogin")).click();
t.end();
csvOutput.write("LoadTest2");
csvOutput.write("Login");
csvOutput.write("" + t.duration());
csvOutput.endRecord();
driver.manage().timeouts().implicitlyWait(4000, TimeUnit.MILLISECONDS);
t.reset();
start = System.currentTimeMillis();
driver.findElement(By.className("log")).click();
t.end();
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.MILLISECONDS);
csvOutput.write("LoadTest2");
csvOutput.write("Go to Administration");
csvOutput.write("" + t.duration());
csvOutput.endRecord();
driver.manage().timeouts().implicitlyWait(7000, TimeUnit.MILLISECONDS);
t.reset();
start = System.currentTimeMillis();
driver.findElement(By.xpath("//a[#class='logout']")).click();
t.end();
csvOutput.write("LoadTest2");
csvOutput.write("Logout");
csvOutput.write("" + t.duration());
csvOutput.endRecord();
/*FileReader fr = new FileReader(new File("C:\\output.csv"));
BufferedReader br = new BufferedReader(fr);
String st;
while ((st = br.readLine()) != null){
System.out.println(st);
}*/
csvOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#After
public void tearDown() throws Exception {
super.tearDown();
driver.quit();
}
}
Here's just one user, I'll make 5 Jar files and start it in JMeter.

Related

Why my selenium function say no Element found

Why if i use same code of affordabilityErrorVerify() in mortgageCalculator() function its working fine but when i use that code in affordabilityErrorVerify() [ same as i posted here ] it says : --> org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#ifrm_13536"}
its weird for me can someone help me how i can make it work
public class test1 extends base {
public WebDriver driver;
public static Logger log =LogManager.getLogger(base.class.getName());
#BeforeTest
public void initialize() throws IOException {
driver = initializeDriver(); // initialize the browser driver based on data.properties file browser value
}
#Test(dataProvider = "dataDriven")
public void mortgageCalculator(String amount, String year, String Frequency, String type, String product,
String term, String rate) throws IOException, InterruptedException {
driver.get(prop.getProperty("url")); // read the data.properties file for get the value of url
driver.manage().window().maximize();
LandingPage l = new LandingPage(driver); // created object for Landing page to access page element
Actions actions = new Actions(driver);
WebElement mainMenu = l.menuBar();
actions.moveToElement(mainMenu);
WebElement subMenu = l.clickLink();
actions.moveToElement(subMenu);
actions.click().build().perform();
// Explicit wait because calculator is in frame and it loads after some time
// so wait until frame is visible
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(#class,'col-12 col-md-9 side-content')]")));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500)");
// switch to frame elements
driver.switchTo().frame(l.switchToFrame());
Thread.sleep(3000);
l.productTabClick().click(); // click on product tab
Thread.sleep(3000);
WebElement money = l.mortgageAmount();
money.click();
money.sendKeys(Keys.CONTROL + "a");
money.sendKeys(Keys.DELETE);
money.sendKeys(amount);
WebElement period = l.mortgageYear();
period.click();
period.sendKeys(Keys.CONTROL + "a");
period.sendKeys(Keys.DELETE);
period.sendKeys(year);
Select s = new Select(l.paymentFrequency());
s.selectByValue(Frequency);
// if data provider send Fixed it will click on fixed radio button otherwise click on variable
if (type == "Fixed") {
l.paymentType().click();
} else {
l.paymentType().click();
}
Select ss = new Select(l.paymentProduct());
ss.selectByValue(product);
Thread.sleep(3000);
driver.switchTo().defaultContent();
js.executeScript("window.scrollBy(0,300)");
driver.switchTo().frame(l.switchToFrame());
Thread.sleep(3000);
WebElement inputOwnRateTerm = l.paymentTerm();
inputOwnRateTerm.click();
inputOwnRateTerm.sendKeys(Keys.CONTROL + "a");
inputOwnRateTerm.sendKeys(Keys.DELETE);
l.paymentTerm().sendKeys(term);
WebElement inputOwnRateValue = l.paymentRate();
inputOwnRateValue.click();
inputOwnRateValue.sendKeys(Keys.CONTROL + "a");
inputOwnRateValue.sendKeys(Keys.DELETE);
l.paymentRate().sendKeys(rate);
inputOwnRateValue.sendKeys(Keys.ENTER);
Thread.sleep(3000);
String actualPayment = l.monthlyPayment().getText();
String actualIOT = l.interestOverTerm().getText();
String actualInterestOverTerm = actualIOT.substring(0, actualIOT.length()-1);
//double actualInterestOverTerm = Math.round(actualIOT)* 10.0) / 10.0;
//System.out.print(actualPayment); // uncomment to see what Mortgage Payment amount function is returning for given data
//System.out.print(actualInterestOverTerm);
//System.out.print(actualIOT);
String totalAmount = amount;
int arg1 = Integer.parseInt(totalAmount);
String mortgageRate = rate;
double arg2 = Double.parseDouble(mortgageRate);
String totalYear = year;
int arg3 = Integer.parseInt(totalYear);
// to find out total Interest over term months based on year
String iot = term;
int iot1 = Integer.parseInt(iot);
int arg4 = iot1 * 12;
// Pass all 4 argument into mortgage calculator to assert actual and expected result
calculator c = new calculator();
double[] expected = c.mortgageCalculator(arg1, arg2, arg3, arg4);
//System.out.println("Mortgage Payment :" + expected[0]); // giving back Mortgage Payment amount from custom function
//System.out.println("Interest over term :" + expected[1]); // giving back Interest over term amount from custom function
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(); // converting numbers into money format [number format]
String act = defaultFormat.format(expected[1]);
String expectedInterestOverTerm = act.substring(0, act.length()-1);
//***********************
// ActualPayment = Getting value from https://www.coastcapitalsavings.com/calculators/mortgage-calculator
// Expected[0] = Getting value from calculator() function which is mortgageCalculator logic file
//***********************
Assert.assertEquals(actualPayment,defaultFormat.format(expected[0])); // Assertion to find out both values are same
Assert.assertEquals(actualInterestOverTerm,expectedInterestOverTerm); // Assertion to find out both values are same
log.info("*************Expected****************");
log.info("Mortgage Payment :" + expected[0]);
log.info("Interest Over Term :" + expectedInterestOverTerm);
log.info("**************Actual*****************");
log.info("Mortgage Payment :" + actualPayment);
log.info("Interest Over Term :" + actualInterestOverTerm);
log.info("_______________________________________");
}
#Test
public void affordabilityErrorVerify() throws InterruptedException
{
LandingPage l = new LandingPage(driver); // created object for Landing page to access page element
JavascriptExecutor js = (JavascriptExecutor) driver;
Thread.sleep(3000);
driver.switchTo().defaultContent();
js.executeScript("window.scrollBy(0,-500)");
Thread.sleep(3000);
driver.switchTo().frame(l.switchToFrame());
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(#class,'col-12 col-md-9 side-content')]")));
Thread.sleep(3000);
l.affordabilityTabClick().click(); // click on affordability tab
Thread.sleep(3000);
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).click();
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).sendKeys("10000");
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).sendKeys(Keys.ENTER);
}
By looking at your code, I have a probable solution to your problem.
There is no priority defined for tests. So in TestNG, if priority is not defined, the test will get executed in alphabetical order. In this case, affordabilityErrorVerify() test will execute first and then mortgageCalculator().
If I observe affordabilityErrorVerify(), there is no method to open URL like driver.get(url) so no page will get open and it will cause NoSuchElementException
A possible answer can be assigned priority to tests
#Test (priority=1, dataProvider = "dataDriven")
public void mortgageCalculator(String amount, String year, String Frequency, String type, String product,
String term, String rate) throws IOException, InterruptedException {
//code
}
#Test (priority=2)
public void affordabilityErrorVerify() throws InterruptedException
{
//code
}
In this as well you have to make sure actions on second test are continuing on same page where test1 ends.
Modify your tests and actions considering flow of test and it will work
Happy coding~

How can take screenshot of new tab once its loaded completly in selenium

#Test
public void testHeaderlinks() throws IOException {
homePage=new HomePage();
homePage.ClickmenuHolidays();
homePage.Clickmenuattraction();
homePage.Clickmenuhotdeal();
String originalHandle = driver.getWindowHandle();
for(String handle : driver.getWindowHandles()) {
if (!handle.equals(originalHandle)) {
driver.switchTo().window(handle);
driver.close();
}
}
driver.switchTo().window(originalHandle);
}
public static void Takescreenshot(String filename) throws IOException {
File file= ((TakesScreenshot))driver.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file,new File("C:\\Users\\User\\Desktop\\POMMabuhayFinal\\src\\main\\java\\Screnshots\\"+filename+".jpg"));
}
In my code i am click hyperlinks in new tab and close those tabs (closing all tabs after all hyperlinks clicks)
My question is how can i take screenshot of opened tabs( i wanna take all new tabs which are open)
Use WebDriverWait to wait for tab/page load and then call your Takescreenshot method while you iterate tabs
#Test
public void testHeaderlinks() throws IOException {
homePage=new HomePage();
homePage.ClickmenuHolidays();
homePage.Clickmenuattraction();
homePage.Clickmenuhotdeal();
String originalHandle = driver.getWindowHandle();
int count = 1;
for(String handle : driver.getWindowHandles()) {
if (!handle.equals(originalHandle)) {
// Initialize WebDriverWait with 15 secs wait timeout or expected wait timeout
WebDriverWait wait = new WebDriverWait(myDriver, 15);
// Wait for page to load
wait.until(webDriver -> ((JavascriptExecutor) myDriver).executeScript("return document.readyState").toString().equals("complete"));
driver.switchTo().window(handle);
// Take screenshot of your current tab
Takescreenshot("tabImage" + String.valueOf(count)) // You can use your own imageName
driver.close();
count++;
}
}
driver.switchTo().window(originalHandle);
}
public static void Takescreenshot(String filename) throws IOException {
File file= ((TakesScreenshot))driver.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file,new File("C:\\Users\\User\\Desktop\\POMMabuhayFinal\\src\\main\\java\\Screnshots\\"+filename+".jpg"));
}
Please Try this
public void TakeScreenShot()
{
try
{
string text = AppDomain.CurrentDomain.BaseDirectory + "\\screenshots\\";
if (!Directory.Exists(text))
{
Directory.CreateDirectory(text);
}
if (Directory.Exists(text))
{
string text2 = text + XYZ+ ".jpeg";
if (File.Exists(text2))
{
File.Delete(text2);
}
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(text2, ScreenshotImageFormat.Jpeg);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

How to continue running my testcases in the same window using selenium C#?

Please help me with this.
My second method is dependent on first method and so on.
I am not using driver.quit() or driver.close()
[TestMethod]
public void CheckInAsDcs()
{
Thread.Sleep(2000);
Assert.AreEqual(driver.Title, "NeuTravel");
var selectDropDown = driver.FindElement(By.Id("viewSelect"));
var dcsOption = driver.FindElements(By.TagName("option"))[1];
//checking for dcs in dropdown
var checkForDcs = driver.FindElement(By.Id("viewSelect"));
dcsOption.Click();
Thread.Sleep(2000);
}
[TestMethod]
public void CreateNewRequest()
{
//calling CheckInAsDcs function
CheckInAsDcs();
//waiting for the web elements to load
Thread.Sleep(10000);
//finding CreateNewRequest button and clicking it
var selectCreateNewReq = driver.FindElements(By.TagName("input"));
selectCreateNewReq[0].Click();
}

TestNG Asserts put under Page Objects are not reflected in the TestNG report for webdriver test

I am working on Java-selenium test framework.
We are calling individual page objects for testing methods viz:
verifyOrderSummary()
These methods sitting inside Page Object will have individual TestNG asserts
Now, when I run my main calling methods / TestNG Tests then, after execution of the test result of the assert is not getting written in the TestNG report.
Kindly advise.
How should I structure my Page Object driven tests, so that- assertings (soft/hard) will get reflected in the final TestNG report.
Many thanks
Hi, Below is one of the key test method( calling various page objects representing various pages):
#Test(dataProvider="BillingDataExcel")
public void dataEntryMethod(String sNo, String sTestCaseName, String sTestDesc, String sAddMedia, String sSupplyVia, String sClock, String sAdvertiser, String sSubtitles, String sBrand, String sPriceModel, String sMarket) throws InterruptedException, IOException {
try{
loginToA5();
navigateToDeliveryDashboard();
softAssert = new SoftAssert();
deliveryLandingPageDataVariant = new DeliveryLandingPageDataVariant(driver);
Thread.sleep(1000);
deliveryLandingPageDataVariant.triggerCreateOrder();
Thread.sleep(1000);
deliveryLandingPageDataVariant.changeCountry(sMarket);
Thread.sleep(1000);
deliveryLandingPageDataVariant.addMedia(sAddMedia, sSupplyVia);
//****XML Driven variant below****
//deliveryLandingPageDataVariant.AddInformation();
deliveryLandingPageDataVariant.AddInformation(sClock,sAdvertiser,sSubtitles,sBrand);
//****XML Driven variant below****
//deliveryLandingPageDataVariant.selectBroadCastDest();
deliveryLandingPageDataVariant.selectBroadCastDest(sNo);
myUtil.TakeSnapShot(driver, "AfterFilling-inData");
deliveryLandingPageDataVariant.submitData();
Thread.sleep(2000);
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
ViewOrderPage viewOrderPage = new ViewOrderPage(driver);
softAssert.assertTrue(viewOrderPage.verifyOrderSummary(sNo,sTestCaseName,myUtil.excelFeederRowCount++));
viewOrderPage.openOrderSummaryAndVerifyDesti(sNo);
/*Below is a Temp hook, before we fix the #After annotation */
driver.close();
driver.quit();
Thread.sleep(1000);
}catch(AssertionError e){
System.out.println("Assertion error or other error -- ");
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
And below is the One of Page Object:
public class ViewOrderPage extends Abstractpage {
XMLDataReader xmlDataReader = new XMLDataReader();
#FindBy(css="#angularHolder > div > div > div.clearfix.pbxs.ng-scope > div > div:nth-child(2) > div > div > div:nth-child(2)")
//#FindBy(xpath=".//*[#id='angularHolder']/div/div/div[1]/div/div[2]/div/div/div[2]")
private WebElement QTYValue;
#FindBy(xpath=".//*[#id='angularHolder']/div/div/div[1]/div/div[3]/div/div[1]/div[2]/span")
private WebElement subTotalValue;
#FindBy(xpath="//button[#data-role='viewReport']")
private WebElement viewOrderSummaryButton;
private final String WAIT_WHEEL_PATH =".//*[#id='angularHolder']/div/div/div[2]/div[2]";
private int i;
String STDCell;
String EXPCell;
String STACell;
private final String DELIVER_TO_STRING=".//*[#id='report']/div/div[2]/div[4]/table/tbody/tr";
public ViewOrderPage(WebDriver driver){
this.driver=driver;
AjaxElementLocatorFactory aFactory= new AjaxElementLocatorFactory(driver, 20);
PageFactory.initElements(aFactory, this);
myWait=new WebDriverWait(driver, 120);
myWait.until(ExpectedConditions.elementToBeClickable(viewOrderSummaryButton));
//myWait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(WAIT_WHEEL_PATH));
}
#SuppressWarnings("finally")
public boolean verifyOrderSummary(String sNo, String sTestCaseName, int feederRowCount) throws Exception{
int subTotal=-1;
int qty=-1;
boolean valueMatched = false;
System.out.println("\n=========================Verify Order Summary Section=================================");
System.out.println("**Quantity =" + getQTY());
System.out.println("**subTotal ="+ getSubTotal());
try {
ExcelUtils.setExcelFile(System.getProperty("user.dir")+"/src/test/java/com/SAPAutomation/testData/BillingData.xlsx","TestResults");
ExcelUtils.setCellData(sNo, feederRowCount, 0);
ExcelUtils.setCellData(sTestCaseName, feederRowCount, 1);
ExcelUtils.setCellData(getQTY(), feederRowCount, 2);
ExcelUtils.setCellData(getSubTotal(), feederRowCount, 3);
System.out.println("Test Results Read: "+ (String.valueOf(ExcelUtils.getCellData(feederRowCount, 4)).toLowerCase()));
if(getSubTotal().toLowerCase().equals("£"+String.valueOf(ExcelUtils.getCellData(feederRowCount, 4)).toLowerCase()+".00")){
valueMatched=true;
System.out.println("\n**Subtotle of "+feederRowCount+" Matched**");
ExcelUtils.setCellData("PASS", feederRowCount, 5);
}else{
ExcelUtils.setCellData("FAIL", feederRowCount, 5);
System.out.println("\n**Subtotle of "+feederRowCount+" didn't match**");
valueMatched=false;
}//end else
// try {
// Assert.assertEquals(getSubTotal(), String.valueOf(ExcelUtils.getCellData(feederRowCount, 4)), "Quantity Matched");
// } catch (Exception e) {
// e.getMessage();
//
// Reporter.log("Assertion error in Verify Order summary:"+ e.getMessage());
// }
} catch (Exception e1) {
e1.printStackTrace();
}finally{
myUtil.takeFieldSnapshot(driver, driver.findElement(By.xpath(".//*[#id='angularHolder']/div/div/div[1]/div")), "OrderSummaryHighlight");
return valueMatched;
}
}
#SuppressWarnings("finally")
private String getQTY(){
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
String QTY = "0";
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try{
return QTY=QTYValue.getText();
}catch(Exception e){
e.getStackTrace();
return QTY;
}
}
private String getSubTotal(){
String subTotal="";
try{
return subTotal = subTotalValue.getText();
}catch (Exception e){
e.getStackTrace();
return subTotal;
}
}
public void openOrderSummaryAndVerifyDesti(String sNo) throws Exception{
String mainWinHande=driver.getWindowHandle();
viewOrderSummaryButton.click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Set<String> handles = driver.getWindowHandles();
for(String handle : handles)
{
if(!mainWinHande.equals(handle))
{
driver.switchTo().window(handle);
String attriAndDestinations[][]=ExcelUtils.getTableArray(System.getProperty("user.dir")+"/src/test/java/com/SAPAutomation/testData/BillingData.xlsx", sNo, myUtil.GLOBAL_MAX_COLUMN_COUNT);
ExcelUtils.setExcelFile(System.getProperty("user.dir")+"/src/test/java/com/SAPAutomation/testData/BillingData.xlsx",sNo);
String destinationCell="";
STDCell="--";
EXPCell="--";
STACell="--";
int broadcasterTableSize= driver.findElements(By.xpath(DELIVER_TO_STRING)).size();
for(i=1;i</*broadcasterTableSize*/attriAndDestinations.length+1;i++){
int xPathDIVCounter=i+2;
//Get Destination
destinationCell=driver.findElement(By.xpath(DELIVER_TO_STRING+"["+xPathDIVCounter+"]/td[2]")).getText();
ExcelUtils.setCellData(destinationCell, i, 3);
System.out.println("\n**DEBUG: Destination Cell value ="+destinationCell);
//Get Attribute
//--STD
STDCell=driver.findElement(By.xpath(DELIVER_TO_STRING+"["+xPathDIVCounter+"]/th[1]")).getText();
ExcelUtils.setCellData(STDCell, i, 4);
System.out.println("\n**DEBUG: STD Cell value ="+STDCell);
//Get Attribute
//--EXP
EXPCell=driver.findElement(By.xpath(DELIVER_TO_STRING+"["+xPathDIVCounter+"]/th[2]")).getText();
ExcelUtils.setCellData(EXPCell, i, 5);
System.out.println("\n**DEBUG: EXP Cell value ="+EXPCell);
//Get Attribute
//--STA ** SPECIAL CASE** TO DO
// EXPCell=driver.findElement(By.xpath(DELIVER_TO_STRING+"["+xPathCounter+"]/th[3]")).getText();
// ExcelUtils.setCellData(STDCell, i, 6);
}//end for
// tallyTableRowsWithNumberOfDestinations(attriAndDestinations.length);
}//end if
}//end for
driver.close(); // close the poped-up report window
driver.switchTo().window(mainWinHande);
}
private void tallyTableRowsWithNumberOfDestinations(int destinationSize){
int rowCount= driver.findElements(By.xpath(DELIVER_TO_STRING)).size();
System.out.println("\n** Table row Count: "+rowCount +"| destinations ArraySize: "+destinationSize);
try {
softAssert.assertEquals(rowCount-1, destinationSize+1, "Table rowcount didn't match with the Number of destinations selected");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void concludeAsserts(){
softAssert.assertAll();
}
}
As mentioned in the comments, you should separate your test logic out of your page objects. The page objects should report or alter the current state of the page, and it's up to the tests to decide whether what the page object reports is correct.
Break your page object method up more so that each one sets or checks one item on the page, then check each of those items from your test...
Assert.AreEqual(thePage.getOrderTotal(), expectedValue1);
Assert.AreEqual(thePage.getOrderItem(1), expectedValue2);
Assert.AreEqual(thePage.getOrderItem(2), expectedValue3);
Assert.AreEqual(thePage.getAnotherThing(), expectedValue4;
...
If you find yourself doing these things over and over again in each test, you may find it useful to bunch these asserts together into a helper method in your test class, which I suspect might be the intended purpose of verifyOrderSummary()

Selenium Browser keeps dying on me

I see other people have been having this issue, by mine seems a bit different than anyone elses as it only is occuring when I run a full suite (fails on like test 20).
if I run a single test or only a few test, the code works just fine.
Otherwise, I get the following stack trace:
org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died.
I am running my code locally and I don't know why it doesn't try to create a new browser. Instead, it just skips all the remaining cucumber steps.
Does anyone know why this would happen?
Here is my setup and teardown steps:
public class Setup_Teardown_steps extends BaseStepClass {
#Before("#selenium")
public void selenium_before_step(Scenario scenario) { //Function responsible for setting the scenario start and global end condition
//Selenium setup
//initialize_selenium_elements();
driver = WebDriver_Singleton.getNewDriver(); //Creates a new Webdriver instance.
driver.manage().window().setSize(new Dimension(1280, 800));
startTime = System.currentTimeMillis();
testData.ClearTestData(); //Clears saved test data
testData.current_scenario = scenario;
}
/**
* After each scenario Hook (except report scenarios) - public cause it has to be.
*/
#After("#selenium")
public void selenium_after_step(Scenario scenario) throws IOException {
endTime = System.currentTimeMillis();
scenario.write("Run time = " + (endTime - startTime)/1000 + " seconds");
if (scenario.isFailed()){
String html_link = driver.getCurrentUrl();
scenario.write("\n");
scenario.write("URL = " + html_link);
try {
byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
} catch (WebDriverException wde) {
System.err.println(wde.getMessage());
} catch (ClassCastException cce) {
cce.printStackTrace();
}
}
driver.close(); //Clears cache and cookies
testData.ClearTestData(); //Clears saved test data
}
}
//WebDriver_Singleton Function below
private static WebDriver create_driver(){
if (driver != null){
driver.close();
}
assign_base_urls();
String browser = System.getProperty("browser") == null ? "ff" : System.getProperty("browser");
switch(browser.toLowerCase()){
case "ff":
case "firefox":
case "mozilla":
driver = new FirefoxDriver();
break;
case "ie":
case "internet explorer":
case "internet_explorer":
driver = new InternetExplorerDriver();
break;
case "chrome":
case "google":
driver = new ChromeDriver();
break;
default:
System.out.println("Defaulting to Firefox browser");
driver = new FirefoxDriver();
}
driver.manage().timeouts().implicitlyWait(implicit_wait_timeouts, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(page_load_timeouts, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(script_timeouts, TimeUnit.SECONDS);
return driver;
}
I looked at the stack trace, was hard to find but the jenkins server was running out of memory.