3

I've been playing around with the Allure framework and I think that if any error/failure happened (basically anything that isn't a pass) I'd like to capture a screenshot.

I'm using Java/Junit/Maven.

I've seen there are various ways of using @Rule to do this, but wasn't sure if this would save the screenshot within the report.

I had thought there would be a testcase status or something I could check as part of the tear down but counldn't find anything.

Anyone have any ideas?

Joseph
  • 541
  • 1
  • 4
  • 31

1 Answers1

3

JUnit rules it is the default way to save screenshots on fail. An example:

@Rule
public TestWatcher screenshotOnFailure = new TestWatcher() {
    @Override
    protected void failed(Throwable e, Description description) {
        makeScreenshotOnFailure();
    }

    @Attachment("Screenshot on failure")
    public byte[] makeScreenshotOnFailure() {
        return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
    }
};
Dmitry Baev
  • 2,270
  • 1
  • 14
  • 24
  • I'll give this a try when I get back - it's certainly a lot simpler than some other examples I found via google. – Joseph Mar 16 '15 at 15:21
  • many thanks for the help - however I get the following error on the line after the Override: "**The method failed(Throwable, Description) of type new TestWatcher(){} must override or implement a supertype method**" - which I can't figure out why. Also, am I being a bit thick, but I haven't been asked to import Override (or does that come from the Rule import?) – Joseph Mar 16 '15 at 18:17
  • Ok the error was that I had an existing import which I hadn't removed and it conflicted. However, no screenshots are generated as this failed seems to be getting called after the `@After` code block (which I use to kill the active browser) - is this a mistake on my part or have I forgot to add something? – Joseph Mar 16 '15 at 19:13
  • 1
    Yep, JUnit executes Rules after the `@After` methods, so you can use `finished` method from `TestWatcher` to kill the browser – Dmitry Baev Mar 16 '15 at 19:48
  • would that mean having to remove all the brower.close() from my existing `@After` methods? or is there some logic I can put in the after (if there has been no error, close browser, else keep it alive)? – Joseph Mar 16 '15 at 19:55
  • `finished` invoked when a test method finishes (whether passing or failing) – Dmitry Baev Mar 16 '15 at 19:58
  • marked as answered - many thanks (if I've done it wrong, let me know and I'll sort the marking thing.) – Joseph Mar 16 '15 at 20:09
  • Can you please suggest the similar approach with TestNG? – Nikunj Aggarwal Aug 03 '16 at 12:34