【Selenium】【Java】Selenium in JUnit ~テスト失敗時にスクリーンショットを撮る~

 ■ サンプル

 SeleniumTestWatcher.java

// TestWatcherを継承したクラス
import java.io.File;

import org.apache.commons.io.FileUtils;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumTestWatcher extends TestWatcher {
   private WebDriver driver;

   public WebDriver getWebDriver() {
      return this.driver;
   }
   
   @Override
   protected void starting(Description description) {
      this.driver = new FirefoxDriver();
   }

   @Override
   protected void finished(Description description) {
      this.driver.quit();
   }

   // ★ここで、テスト失敗時にスクリーンショットを撮る★
   @Override
   protected void failed(Throwable throwable, Description description) {
      super.failed(throwable, description);
      this.takeScreenShot(String.format("%s_%s.png", description.getClassName(), description.getMethodName()));
   }
   
   protected void takeScreenShot(String fileName) {
      try {
         FileUtils.copyFile(
               ((TakesScreenshot) this.driver).getScreenshotAs(OutputType.FILE),
               new File(String.format("C:/temp/%s", fileName)));
      } catch (java.io.IOException e) {
      }
   }
}

 SeleniumSampleTest.java

// テストコード例
import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;

public class SeleniumSampleTest {
   private WebDriver driver;
   
   @Rule
   public SeleniumTestWatcher watcher = new SeleniumTestWatcher();

   @Before
   public void setUp() throws Exception {
      this.driver = watcher.getWebDriver();
   }

   @After
   public void tearDown() throws Exception {
   }

   @Test
   public void test() throws InterruptedException {
      this.driver.get("https://www.yahoo.co.jp/");
      Thread.sleep(3000L);
      fail("Not yet implemented");
   }
}

 参考文献

http://softwaretest.jp/labo/tech/labo-298/