title: Capture WebDriver Screenshots When Running Parallel Tests With TestNG
body: <p>I am currently capturing screenshots on failure and success in TestNG by way of overriding the TestListenerAdapter methods onTestFailure, and onTestSuccess respectively. In order to do this you need to specify which driver you want to take a screenshot of.</p>
  
  <p><strong>My question:</strong> Is there a good way to capture screenshots when running tests in parallel on the method level?</p>
  
  <p>In order to run tests in parallel, each individual test needs a unique driver instance. So, at any given time you have x number of driver instances running. When it comes time to capture a screenshot, how do you determine which driver to use?</p>
  
  <p>Code excerpts below:</p>
  
  <pre><code>public class OnFailureListener extends TestListenerAdapter {    
  
  @Override   
  public void onTestFailure(ITestResult tr) {     
     Screenshots.captureScreenshot(tr);
  
     super.onTestFailure(tr);             
  }
  </code></pre>
  
  <p>--</p>
  
  <pre><code>public static void captureScreenshot(ITestResult tr) {
     WebDriver driver = TestClass.driver;
  
     if (driver instanceof TakesScreenshot) {                                                                                                         
        String filename = "path/to/screenshot/file";
  
     try {
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File(filename));
     } catch (IOException e) { e.printStackTrace(); }
  }
  </code></pre>