我想使用Google搜索执行API测试。

时间:2018-09-10 12:34:25

标签: web-api-testing

我想使用Google搜索执行API测试。在google.com中输入文本,然后从结果中搜索Wikipedia链接并导航至Wikipedia链接。请建议如何使用Rest Assured API使用Java Selenium执行此操作

1 个答案:

答案 0 :(得分:0)

在问之前,您必须先阅读并尝试一下。看来您根本没有尝试过任何东西,也不清楚如何开始。所以我帮你

package navi;

import java.awt.AWTException;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Google2Wiki {

    // defines driver
    private static WebDriver driver;

    // new wait for 5 seconds
    WebDriverWait wait5s = new WebDriverWait(driver,5);

    @BeforeClass
    public static void setUpClass() {
        // path to chromedriver.exe
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\pburgr\\Desktop\\chromedriver\\chromedriver.exe");
        // new ChromeOptions instance
        ChromeOptions options = new ChromeOptions();
        // optionaly an existing browser profile can be used instead of a temporary profile
        options.addArguments("user-data-dir=C:\\Users\\pburgr\\AppData\\Local\\Google\\Chrome\\User Data");
        // new ChromerDriver instance with oprtions
        driver = new ChromeDriver(options);
        // maximizes current window
        driver.manage().window().maximize();}   
    @Before
    public void setUp() {}
    @After
    public void tearDown() {}
    @AfterClass
    public static void tearDownClass() {driver.close();driver.quit();}
    @Test
    public void autofill_first_value () throws InterruptedException, AWTException {

        // get Google.com
        driver.get("https://www.google.com/");
        // wait up to 5 seconds for input field
        WebElement fld_search = wait5s.until(ExpectedConditions.elementToBeClickable(By.id("lst-ib")));

        // enterring text to search
        fld_search.click();
        fld_search.sendKeys("french military victories wiki");

        // hitting the search button
        WebElement btn_search = driver.findElement(By.name("btnK"));
        btn_search.click();

        // get the first link as WebElement
        WebElement first_link = wait5s.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"rso\"]/div[1]/div/div[1]/div/div/h3/a")));
        first_link.click();

        // try to wait up to 5 seconds until reaching wiki
        try {wait5s.until(ExpectedConditions.urlContains("wikipedia.org"));} catch (TimeoutException e) {}
    }
}