-1

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();
        }


}
user2451016
  • 1,857
  • 3
  • 20
  • 44
  • 2
    Asserts inside of Test Objects is bad practice. Asserts go into the test! – SiKing Feb 10 '15 at 15:57
  • Thanks for your valuable comment. But in that case, say- I want to verify 2-3 things in one method. ex.- result values populated under various column. Then how to achieve this, as usually page object returns a simple flag Boolean, int, String etc. Kindly provide some example. Many thanks – user2451016 Feb 10 '15 at 16:37
  • 1
    Sounds like your Page Objects are designed wrong. Kindly provide your code, and a specific question. Have a careful read through [ask]. – SiKing Feb 10 '15 at 16:40
  • Hi, Thanks for your kind advise so far. I now have provided the code. Alongwith previous query, I now have additional query: If we do not have to do the verification activity in the Page Objects & instead if it has to happen in the calling testNG test method(s) then, is it possible to have a child, sub-method in TestNG, which can do the specific job & can be called multiple time from the parent TestNG method viz- verifyOrderSummary(sItemNo). Kindly suggest. Many Thanks – user2451016 Feb 11 '15 at 17:07

1 Answers1

0

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()