テストの自動化はモジュールのユニットテストまではできても、画面の自動化まで手が回っていないことが多いだろう。
画面のテスト自動化といえばSeleniumが有名だが、しばらく触れないうちにバージョン2になっており、進化していた。
WebDriverと組み合わせるとブラウザを外部から操作することができるので、人間の実機操作に近い挙動でテストができる。
とりあえず、適当な画面にアクセスして内部の要素を表示させるサンプル。
IDで見つけられればXpathは不要。
import java.io.File;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SeleniuimTest {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.example.com/");
// 30秒待つ設定
Wait<WebDriver> wait = new WebDriverWait(driver, 30);
// sideMenuという要素がクリックできるようになるまでまつ(ただし30秒)
WebElement button = wait.until(ExpectedConditions
.elementToBeClickable(By.className("sideMenu")));
// firebugのxpathをそのままでOK
System.out.println(driver.findElement(By.xpath("/html/body/div/div/div[2]/div[2]/div[1]/ul/li[1]/a")).getText());
// 複数処理する場合
List<WebElement> elements = driver.findElements(By.xpath("/html/body/div/div/div[2]/div[2]/div[1]/ul/li"));
for (WebElement webElement : elements) {
System.out.println(webElement.getText());
}
// スクリーンショットも取れる。
try {
FileUtils.copyFile(
((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE),
new File("d:/screen.jpg"));
} catch (Exception e) {
}
Thread.sleep(10000);
driver.quit();
}
}