Skip to content

Instantly share code, notes, and snippets.

@juherr
Created October 20, 2015 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juherr/600edc68c32ba6a3f419 to your computer and use it in GitHub Desktop.
Save juherr/600edc68c32ba6a3f419 to your computer and use it in GitHub Desktop.
TestNG: No need of listener by class
package test;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners(ScreenshotMaker.class)
public class BeforeScreenshotTest implements Screen {
public String getDriver() {
return "driver of BeforeScreenshotTest";
}
@BeforeMethod
public void beforeMethod() {
Assert.fail("BOUM");
}
@Test
public void test() { }
}
package test;
public interface Screen {
String getDriver();
}
package test;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
public class ScreenshotMaker implements IInvokedMethodListener {
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
}
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (testResult.getStatus() == ITestResult.FAILURE) {
Object testInstance = testResult.getInstance();
if (testInstance instanceof Screen) {
Screen screen = (Screen) testInstance;
System.out.println("after invocation of " +testResult.getName());
System.out.println("\t" + screen.getDriver());
}
}
}
}
package test;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners(ScreenshotMaker.class)
public class ScreenshotTest implements Screen {
public String getDriver() {
return "driver of ScreenshotTest";
}
@Test
public void test() {
Assert.fail("BOUM");
}
}
@hubertgrzeskowiak
Copy link

Interesting. I didn't know applying listeners with annotation applies the listener once for whole suite. This is actually the cleanest way to add a screenshot listener I've seen so far! GJ and Thanks

@aadilc33
Copy link

Thanks mate your awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment