Bird
Raised Fist0
Selenium Javatesting~20 mins

Screenshot attachment on failure in Selenium Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Screenshot Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output when this Selenium test fails?
Consider this Java Selenium test snippet that takes a screenshot on failure. What will be the result if the assertion fails?
Selenium Java
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.*;
import java.io.File;
import org.apache.commons.io.FileUtils;

public class ScreenshotTest {
    WebDriver driver;

    @BeforeMethod
    public void setup() {
        driver = new ChromeDriver();
        driver.get("https://example.com");
    }

    @Test
    public void testTitle() throws Exception {
        try {
            Assert.assertEquals(driver.getTitle(), "Wrong Title");
        } catch (AssertionError e) {
            File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(src, new File("failure.png"));
            throw e;
        }
    }

    @AfterMethod
    public void teardown() {
        driver.quit();
    }
}
ATest fails with AssertionError and a screenshot file named 'failure.png' is saved in the project folder.
BTest passes because the screenshot is taken and the error is caught, so no failure is thrown.
CTest fails but no screenshot is saved because FileUtils.copyFile throws IOException that is not handled.
DTest fails and throws a NullPointerException because driver is not initialized.
Attempts:
2 left
💡 Hint
Look at how the AssertionError is caught and rethrown after saving the screenshot.
❓ assertion
intermediate
1:30remaining
Which assertion correctly verifies screenshot file creation after failure?
After a Selenium test fails and saves a screenshot named 'error.png', which assertion correctly checks that the screenshot file exists?
Selenium Java
File screenshot = new File("error.png");
AAssert.assertFalse(screenshot.isFile());
BAssert.assertEquals(screenshot.length(), 0);
CAssert.assertTrue(screenshot.exists());
DAssert.assertNull(screenshot);
Attempts:
2 left
💡 Hint
Check if the file physically exists on disk.
🔧 Debug
advanced
2:00remaining
Why does this screenshot capture code throw IOException?
This Selenium Java code snippet throws IOException during screenshot capture. What is the cause?
Selenium Java
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("/invalid_path/failure.png"));
AFileUtils.copyFile requires a third argument for overwrite permission.
BThe driver is not cast correctly to TakesScreenshot.
CThe source file 'src' is null because screenshot failed.
DThe destination path '/invalid_path/failure.png' does not exist or is not writable.
Attempts:
2 left
💡 Hint
Check the file path permissions and existence.
❓ framework
advanced
1:30remaining
Which TestNG listener interface is best to implement automatic screenshot on test failure?
You want to automatically capture screenshots on test failures in TestNG without modifying each test method. Which listener interface should you implement?
AISuiteListener
BITestListener
CIAnnotationTransformer
DIInvokedMethodListener
Attempts:
2 left
💡 Hint
Look for listener that reacts to test method results.
🧠 Conceptual
expert
1:00remaining
What is the main benefit of attaching screenshots to test reports on failure?
Why is attaching screenshots to automated test failure reports considered a best practice in software testing?
AIt provides visual evidence of the failure, helping faster debugging and communication.
BIt reduces the test execution time by skipping logs.
CIt automatically fixes UI bugs by capturing screenshots.
DIt prevents tests from failing by retrying the failed steps.
Attempts:
2 left
💡 Hint
Think about how screenshots help developers and testers understand failures.

Practice

(1/5)
1. What is the main purpose of taking a screenshot on test failure in Selenium Java?
easy
A. To automatically fix the test errors
B. To speed up the test execution
C. To visually capture the state of the application at failure
D. To reduce the size of the test report

Solution

  1. Step 1: Understand the role of screenshots in testing

    Screenshots help testers see what the application looked like when a test failed.
  2. Step 2: Identify the benefit of visual evidence

    This visual evidence helps diagnose issues faster and more clearly than logs alone.
  3. Final Answer:

    To visually capture the state of the application at failure -> Option C
  4. Quick Check:

    Screenshot = Visual failure evidence [OK]
Hint: Screenshots show what failed visually, not fix or speed tests [OK]
Common Mistakes:
  • Thinking screenshots fix errors automatically
  • Believing screenshots speed up tests
  • Assuming screenshots reduce report size
2. Which Selenium interface is used to capture screenshots in Java?
easy
A. WebDriver
B. JavascriptExecutor
C. Alert
D. TakesScreenshot

Solution

  1. Step 1: Recall Selenium interfaces for screenshots

    The TakesScreenshot interface provides the method to capture screenshots.
  2. Step 2: Differentiate from other interfaces

    Other interfaces like WebDriver control browser, Alert handles popups, and JavascriptExecutor runs JS scripts.
  3. Final Answer:

    TakesScreenshot -> Option D
  4. Quick Check:

    TakesScreenshot = Capture screenshots [OK]
Hint: Use TakesScreenshot interface to capture images [OK]
Common Mistakes:
  • Using WebDriver directly for screenshots
  • Confusing Alert or JavascriptExecutor with screenshot capture
  • Not casting driver to TakesScreenshot
3. What will happen if you run this code snippet after a test failure?
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File("screenshots/fail.png"));
medium
A. Compilation error due to missing cast
B. Screenshot saved as fail.png in screenshots folder
C. Runtime error because FileUtils is undefined
D. Screenshot saved but file name is random

Solution

  1. Step 1: Analyze the screenshot capture code

    The driver is cast to TakesScreenshot and screenshot saved as a file named "fail.png" in the "screenshots" folder.
  2. Step 2: Check for errors or randomness

    FileUtils.copyFile copies the screenshot correctly; file name is fixed as "fail.png" so no randomness.
  3. Final Answer:

    Screenshot saved as fail.png in screenshots folder -> Option B
  4. Quick Check:

    Code saves fixed-name screenshot file [OK]
Hint: Casting driver and copyFile saves fixed screenshot file [OK]
Common Mistakes:
  • Forgetting to cast driver to TakesScreenshot
  • Not importing or defining FileUtils
  • Expecting random file names without code for it
4. Identify the error in this code snippet for saving a screenshot on failure:
File srcFile = driver.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File("screenshots/error.png"));
medium
A. driver must be cast to TakesScreenshot before calling getScreenshotAs
B. FileUtils.copyFile method does not exist
C. OutputType.FILE is invalid for screenshots
D. File path must be absolute, not relative

Solution

  1. Step 1: Check method call on driver

    The getScreenshotAs method belongs to TakesScreenshot, so driver must be cast before calling it.
  2. Step 2: Verify other parts

    FileUtils.copyFile exists and OutputType.FILE is correct. Relative paths are allowed if folder exists.
  3. Final Answer:

    driver must be cast to TakesScreenshot before calling getScreenshotAs -> Option A
  4. Quick Check:

    Cast driver to TakesScreenshot before screenshot [OK]
Hint: Always cast driver to TakesScreenshot before getScreenshotAs [OK]
Common Mistakes:
  • Calling getScreenshotAs directly on WebDriver
  • Assuming OutputType.FILE is wrong
  • Thinking relative paths cause errors
5. You want to attach a screenshot to your test report only when a test fails. Which approach correctly implements this in Selenium Java with TestNG?
@AfterMethod
public void tearDown(ITestResult result) {
  if (result.getStatus() == ITestResult.FAILURE) {
    File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    File dest = new File("screenshots/" + result.getName() + ".png");
    FileUtils.copyFile(src, dest);
    // Attach dest to report here
  }
  driver.quit();
}
hard
A. This code saves screenshot only on failure and attaches it correctly
B. Screenshot is saved on every test, not just failures
C. FileUtils.copyFile will throw error without try-catch
D. result.getName() returns null, so file name is invalid

Solution

  1. Step 1: Check condition for failure

    The code checks if test status is FAILURE before taking screenshot, so it runs only on failures.
  2. Step 2: Verify screenshot saving and naming

    Screenshot saved with test method name, which is valid. Attaching to report is indicated as a comment.
  3. Step 3: Confirm no errors in logic

    FileUtils.copyFile may throw IOException but typically handled or declared; this snippet focuses on logic correctness.
  4. Final Answer:

    This code saves screenshot only on failure and attaches it correctly -> Option A
  5. Quick Check:

    Screenshot on failure only with correct naming [OK]
Hint: Use ITestResult.FAILURE check to save screenshots only on failure [OK]
Common Mistakes:
  • Taking screenshots regardless of test result
  • Not handling exceptions from file operations
  • Assuming getName() returns null
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard