I have to verify an integer value on a page with different clients using dataproviders. I am using softassert, so that the execution doesn't stop. however, when one softassert fails (intentionally) in first iteration, the subsequent iteration fails (should pass) abruptly and throws the exact same assertion error as was thrown in first iteration. but if first iteration passes, second continues properly. Where could be the issue ?
#BeforeMethod
public void beforeMethod(Method method) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\a0136300\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
config = new Configreader();
driver.manage().deleteAllCookies();
}
#DataProvider(name = "TestMSSData")
public Object [][] getData(){
Object [][] data=new Object[2][6];
data[0][0]="url1";
data[0][1]="client1";
data[0][2]="Retail Eligibles : 2018";
data[0][3]="E1";
data[0][4]="Maria_Fake";
data[0][5]=7937;
data[1][0]="url2";
data[1][1]="client2";
data[1][2]="ACTIVE- FAC : 2018";
data[1][3]="E2";
data[1][4]="Tad_Fake";
data[1][5]=4761;
return data;
}
#Test(dataProvider = "TestMSSData")
public void Manager_Self_Service(String url, String client, String eliggrp, String empnumber, String firstname, Integer SSN) throws Exception {
driver.get(url);
try {
String headertex = driver.findElement(By.xpath("/html/body/div[2]/div[1]/div[1]/h3")).getText();
Assert.assertEquals(headertex, "Log On ");}
catch (NoSuchElementException e){
throw new AssertionError("Error in loading URL", e);
}
driver.manage().window().maximize();
RIMethods obj3 =new RIMethods(driver, config);
obj3.Login();
//Verify last 4 digits of SSN
String sn = driver.findElement(By.name("eeSsn3")).getAttribute("value");
int socialsecurity = Integer.parseInt(sn);
s_assert.assertEquals(socialsecurity, SSN, "SSN last four digits did not match");
//verify the header for Future benefits
if(driver.findElement(By.xpath("/html/body/div[4]/div[2]/div[1]/div[1]")).getText().contains("Future Benefits Summary"))
System.out.println("Future Benefits summary header is correct");
else
System.out.println("header is incorrect");
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
s_assert.assertAll();
}
#AfterMethod
public void cleanUp(){
driver.quit();
}
Ahh, its been a full day struggling to get this one and the solution is too simple.
To let it work, I created the softassert object inside the Test method instead of defining at class level, not sure how it affects but its working fine now.
I'm writing a framework with page object. I have a lot of ajax, so in order to get rid of ugly Thread.sleep(5000), I created an extension method, which waits until an element is visible and clicks on it, otherwise it throws an error. But I suspect that there is an error in my code, because it always thrown an error.
public static void WaitForVisible(this IWebElement element, int timeoutSec = 10)
{
var startTime = DateTime.Now;
while ((DateTime.Now - startTime) > TimeSpan.FromSeconds(timeoutSec))
{
if (element.Displayed)
return;
}
throw new Exception("Element wasn't displayed after '" + timeoutSec + "'!");
}
public static void ClickWithWait(this IWebElement element)
{
WaitForVisible(element);
element.Click();
}
Could you please tell what am I doing wrong?
Please try this method.
WebDriverWait wait = new WebDriverWait(driver, 10);
try {
WebElement element= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("someid")));
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
I am testing like 100 url everything is working good. my problem is when the test starts it get web url from notepad then open the url here my process is to check the login or not in some case if the for example 10th url shows 404 error the test terminate here it cant process further urls. Any solution for this process...
my codes
public class File {
#Test(dataProvider="testdata")
public void sum(String url)
{
System.out.println(url);
}
#DataProvider
public Object[][] testdata(){
int count=20;
Object[][] obj = new Object[count][1];
for(int i=0;i<=count;i++)
{
String fileName = "E:\\ework\\Web\\bin\\Websearch\\test.txt";
try {
String line = null;
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
String[] abs={line};
int size = abs.length;
for(int j=0;j<=size;j++)
{
obj[i][0]=abs[j];
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
`}
return obj;
}
}
thank you.:)
If you are using framework like TestNG then look at DataProviders for the same.
Use Try{} Catch(Exception e){} block. Insert your assertion in try block and once the assertion fails then try to capture the exception in some list or other data structure and after all urls are processed then iterate over the exception list and report it in your Reports or logs.
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()
I am trying to take a screenshot for failure methods and also want to put the same in my Report, I am able to take the screenshot but unable to show the same in HTML report. Following is my code, friends any clue on this ?
public class SB1 {
private static Logger logger = Logger.getLogger(SB1.class);
WebDriver driver = new FirefoxDriver();
#Test
public void Testone() {
driver.get("http://www.google.com/");
assert false;
}
public void catchExceptions(ITestResult result) {
System.out.println("result" + result);
String methodName = result.getName();
System.out.println(methodName);
if (!result.isSuccess()) {
try {
String failureImageFileName = new SimpleDateFormat("MM-dd-yyyy_HH-ss").format(new GregorianCalendar().getTime())+ ".png";
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(failureImageFileName));
String userDirector = System.getProperty("user.dir") + "/";
Reporter.log("<a href=\""+ userDirector + failureImageFileName +"\"><img src=\"file:///" + userDirector
+ failureImageFileName + "\" alt=\"\""+ "height='100' width='100'/> "+"<br />");
Reporter.setCurrentTestResult(null);
} catch (IOException e1) {
e1.printStackTrace();
}
}
Have you set ESCAPE_PROPERTY to false? This is what you will have to do if you want reportng to post the screenshot -
private static final String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
and in your setUp-
System.setProperty(ESCAPE_PROPERTY, "false");
I tried this. It seems like if you set the System Property to false, it removes the escaping from the ENTIRE log... From what I can tell, the report is generated after the test, with whatever the system property is set to at the time. I want to insert the screenshot (which worked with above code) but I do not want to remove the other formatting (br tags).
You can use following code.
Reporter.log("<br>Chrome driver launched for ClassOne</br>");
Or you can use customize method, where you do not need to append the br tag everytime, use following customized method.
public void customLogReport(String testCaseDescription) throws Exception{
try{
Reporter.log("<br>" + testCaseDescription + "</br>");
}catch(Exception e){
e.printStackTrace();
}
}