LoginSignup
7
6

More than 5 years have passed since last update.

Windows×IntelliJ×KotlinでSelenium環境構築

Last updated at Posted at 2018-03-16

はじめに

ちょっとレベリングをサボりたく
UIテストを自動化したくてSelenium環境作ったので書きたいと思います。
Kotlinで書いてますがJavaでも同じようにできます。

環境

まずは自分のPC環境(2018年3月時点)
- Windows:10
- IntelliJ:2017.2.6
- kotlin:1.2.21
- ChromeDriver:2.36
- Chrome:65

環境構築

まずはIntelliJでプロジェクトを作ります。
image.png
GroupidとArtifactidを入力して、プロジェクトを作成。

build.gradleにSeleniumのライブラリを追加します。

compile "org.seleniumhq.selenium:selenium-java:3.5.3"

次にChromeDriverをダウンロードします。インストール済みのChromeに対応したバージョンのものが必要です。
https://sites.google.com/a/chromium.org/chromedriver/downloads

ダウンロードした、chromedriver.exeをプロジェクトに入れます。
今回はプロジェクトのルートにdriverというディレクトリを作成してその中に入れました。

次にテストコードを作成します。
Chromeの実行ファイルのパス、先ほどダウンロードしたChromeDriverのパスを入力する必要があります。

SeleniumSample.kt
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions

class SeleniumSample {
    private lateinit var driver: WebDriver

    @Before
    fun setUp() {
        //chrome driverの指定
        System.setProperty("webdriver.chrome.driver", ".\\driver\\chromedriver.exe")

        driver = ChromeDriver(ChromeOptions().apply {
            //chromeのパスを指定
            setBinary(java.io.File("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"))
        })
    }

    @After
    fun tearDown() {
        driver.quit()
    }

    @Test
    fun test_sample() {
        driver.get("https://www.yahoo.co.jp/")
        Thread.sleep(1000)
    }
}

あとは、コードfun test_sample()の左側にある実行ボタンを押すとChromeが起動しYahoo!Japanが表示されます。
image.png
以上環境構築完了です。

おわりに

手でポチポチやっていたのを自動化できるとめちゃくちゃ楽になりました。
たまに安定しなくなったりしますが、Chromeが自動更新したりしてて対応バージョンのdriverに更新したりすると治ったりしました。

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6