天天看點

JAVA+selenium+testng 斷言封裝及調用

package POM;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

public class Assert{

    public WebDriver driver;

    public void setUp() throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "chromedriver.exe存放路徑");
        ChromeOptions options = new ChromeOptions ();
        options.addArguments ( "--test-type","--start-maximized" );
        driver = new ChromeDriver ( options );

        driver.manage().window().maximize();

        driver.get ( "登入連接配接" );
        Thread.sleep(2000);

        driver.findElement(By.xpath("使用者名路徑")).sendKeys("使用者名");
        //輸入密碼
        driver.findElement(By.xpath("密碼路徑")).sendKeys("密碼");
        //點選登入按鈕
        driver.findElement(By.xpath("登入按鈕路徑")).click();

        Thread.sleep(2000);
    }
    public void shutDown(){
        //關閉浏覽器
        driver.close();
        //關閉浏覽器驅動
        driver.quit();
    }
   public void Asserta(String expectition,String  actual,String massage){
        WebElement element= driver.findElement(By.xpath(actual));
        element.getText();
        try {
            Assert.assertEquals(element.getText(),expectition);
        }catch (AssertionError e){
            System.out.println(massage+e.getMessage());
        }

    }
           

進行調用

package POM;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;


public class Boass_test {
        Assert om = new Assert();

        @BeforeTest
        public void setUp() throws InterruptedException {
            om.setUp();
        }

        @AfterTest
        public void shuDown() throws InterruptedException {
            Thread.sleep(5000);
            om.Quit();
        }

        @Test(priority = 1)
        public void FindBrand() {
            om.Asserta("Wehag", "你定位元素的位置","你定位的位置沒有找到你想要的内容");
        }
    }

           

結果

JAVA+selenium+testng 斷言封裝及調用

注意:要保證Java檔案在同一個包下,要不引用方法時,會報空指針異常。不同包下,需要導入包對應的類

繼續閱讀