Best Testng code snippet using org.testng.Interface IHookCallBack
Source:AbstractTestNgSpringContextTests.java  
1package selenium.boot.test;2import com.google.common.base.Throwables;3import lombok.AccessLevel;4import lombok.Setter;5import org.slf4j.Logger;6import org.slf4j.LoggerFactory;7import org.springframework.context.ApplicationContext;8import org.springframework.context.ApplicationContextAware;9import org.springframework.lang.Nullable;10import org.springframework.test.context.TestContextManager;11import org.testng.IHookCallBack;12import org.testng.IHookable;13import org.testng.ITestContext;14import org.testng.ITestResult;15import org.testng.SkipException;16import org.testng.annotations.AfterClass;17import org.testng.annotations.AfterMethod;18import org.testng.annotations.BeforeClass;19import org.testng.annotations.BeforeMethod;20import org.testng.annotations.BeforeSuite;21import org.testng.annotations.BeforeTest;22import org.testng.xml.XmlTest;23import java.lang.reflect.InvocationTargetException;24import java.lang.reflect.Method;25/**26 * Abstract base test class which integrates the <em>Spring TestContext Framework</em>27 * with explicit {@link org.springframework.context.ApplicationContext} testing support in a <strong>TestNG</strong>28 * environment.29 * <p>30 * Concrete subclasses:31 * <ul>32 *     <li>Typically declare a class-level {@link org.springframework.test.context.ContextConfiguration33 *         @ContextConfiguration} annotation to configure the34 *         {@linkplain org.springframework.context.ApplicationContext application context}35 *         {@linkplain org.springframework.test.context.ContextConfiguration#locations() resource locations}36 *         or {@linkplain org.springframework.test.context.ContextConfiguration#classes() annotated classes}.37 *         <em>If your test does not need to load an application context, you may choose to omit the38 *         {@code @ContextConfiguration} declaration and to configure the appropriate39 *         {@link org.springframework.test.context.TestExecutionListeners TestExecutionListeners} manually.</em>40 *     </li>41 *     <li>Must have constructors which either implicitly or explicitly delegate to {@code super();}.</li>42 * </ul>43 * <p>44 * The following {@link org.springframework.test.context.TestExecutionListeners TestExecutionListeners} are configured by default:45 * <p>46 * <ul>47 *     <li>{@link OverrideDirtiesContextBeforeModesTestExecutionListener}48 *     <li>{@link OverrideDependencyInjectionTestExecutionListener}49 *     <li>{@link org.springframework.test.context.support.DirtiesContextTestExecutionListener}50 * </ul>51 *52 * @author Sam Brannen53 * @author Juergen Hoeller54 * @author <a href="mailto:solmarkn@gmail.com">Dani Vainstein</a>55 * @version %I%, %G%56 * @see org.springframework.test.context.ContextConfiguration57 * @see org.springframework.test.context.TestExecutionListeners58 * @see OverrideDirtiesContextBeforeModesTestExecutionListener59 * @see OverrideDependencyInjectionTestExecutionListener60 * @see org.springframework.test.context.support.DirtiesContextTestExecutionListener61 * @see org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests62 * @since 1.063 */64public class AbstractTestNgSpringContextTests implements IHookable, ApplicationContextAware65{66    //region initialization and constructors section67    //region Static definitions, members, initialization and constructors68    //---------------------------------------------------------------------69    // Static definitions, members, initialization and constructors70    //---------------------------------------------------------------------71    protected final Logger log = LoggerFactory.getLogger(  getClass().getName() );72    private final TestContextManager testContextManager;73    /**74     * The {@link ApplicationContext} that was injected into this test instance75     * via {@link #setApplicationContext(ApplicationContext)}.76     */77    @Nullable78    @Setter( AccessLevel.PUBLIC )79    protected ApplicationContext applicationContext;80    @Nullable81    private Throwable testException;82    /**83     * Construct a new AbstractTestNGTestContext instance and initialize84     * the internal {@link org.springframework.test.context.TestContextManager} for the current test class.85     */86    public AbstractTestNgSpringContextTests()87    {88        this.testContextManager = new TestContextManager( getClass() );89    }90    //endregion91    //region TestNG configuration methods92    //---------------------------------------------------------------------93    // TestNG configuration methods94    //---------------------------------------------------------------------95    @BeforeSuite( alwaysRun = false )96    public static void alwaysBeforeSuite() {}97    @BeforeSuite(98            enabled = true,99            alwaysRun = true100    )101    public final void springTestContextBeforeSuite( ITestContext testContext, XmlTest suiteXml ) throws Exception102    {103        try104        {105            System.out.println( "AbstractTestNGSpringContextTests.beforeSuite" );106        }107        catch( Exception e )108        {109            throw e;110        }111    }112    @BeforeTest(113            enabled = true,114            alwaysRun = true115    )116    public final void springTestContextBeforeTest( ITestContext testContext ) throws Exception117    {118        try119        {120            System.out.println( "AbstractTestNGSpringContextTests.springTestContextBeforeTest" );121        }122        catch( Exception e )123        {124            Throwables.throwIfInstanceOf( e, SkipException.class );125            throw e;126        }127    }128    @BeforeClass(129            alwaysRun = true,130            description = "Delegates to the configured TestContextManager to call #beforeTestClass() callbacks."131    )132    protected void springTestContextBeforeTestClass( ITestContext context ) throws Exception133    {134        try135        {136            this.testContextManager.beforeTestClass();// context );137        }138        catch( Exception e )139        {140            Throwables.throwIfInstanceOf( e, SkipException.class );141            throw e;142        }143    }144    @BeforeClass(145            alwaysRun = true,146            description = "Delegates to the configured TestContextManager to #prepareTestInstance(Object) prepare this test" +147                                  "instance prior to execution of any individual tests, for example for injecting dependencies, etc.",148            dependsOnMethods = "springTestContextBeforeTestClass"149    )150    protected void springTestContextPrepareTestInstance( ITestContext context ) throws Exception151    {152        try153        {154            this.testContextManager.prepareTestInstance( this );//, context );155        }156        catch( Exception e )157        {158            Throwables.throwIfInstanceOf( e, SkipException.class );159            throw e;160        }161    }162    @BeforeMethod(163            alwaysRun = true,164            description = "Delegates to the configured TestContextManager to #beforeTestMethod(Object, Method) pre-process " +165                                  "the test method before the actual test is executed."166    )167    protected void springTestContextBeforeTestMethod( ITestContext context, Method testMethod, Object[] parameters ) throws Exception168    {169        try170        {171            this.testContextManager.beforeTestMethod( this, testMethod );172        }173        catch( Exception e )174        {175            Throwables.throwIfInstanceOf( e, SkipException.class );176            throw e;177        }178    }179    /**180     * Delegates to the configured {@link TestContextManager} to181     * {@linkplain TestContextManager#afterTestMethod(Object, Method, Throwable)182     * post-process} the test method after the actual test has executed.183     *184     * @param testMethod the test method which has just been executed on the test instance185     *186     * @throws Exception allows all exceptions to propagate187     */188    @AfterMethod(189            alwaysRun = true,190            description = "Delegates to the configured TestContextManager to post-process methods.\n" +191                                  "the test method after the actual test has executed." )192    protected void springTestContextAfterTestMethod( Method testMethod ) throws Exception193    {194        try195        {196            System.out.println( "AbstractTestNGSpringContextTests.springTestContextAfterTestMethod" );197            // this.testContextManager.afterTestMethod( this, testMethod, this.testException );198        }199        finally200        {201            this.testException = null;202        }203    }204    /**205     * Delegates to the configured {@link TestContextManager} to call206     * {@linkplain TestContextManager#afterTestClass() 'after test class'} callbacks.207     *208     * @throws Exception if a registered TestExecutionListener throws an exception209     */210    @AfterClass( alwaysRun = true, description = " Delegates to the configured  TestContextManager to call after test class callbacks")211    protected void springTestContextAfterTestClass() throws Exception212    {213        this.testContextManager.afterTestClass();214    }215    //endregion216    //region Implementation of IHookable interface217    //---------------------------------------------------------------------218    // Implementation of IHookable interface219    //---------------------------------------------------------------------220    /**221     * Delegates to the {@linkplain IHookCallBack#runTestMethod(ITestResult) test method} in the supplied222     * {@code callback} to execute the actual test and then tracks the exception thrown during test execution, if any.223     *224     * @see org.testng.IHookable#run(IHookCallBack, ITestResult)225     */226    @SuppressWarnings( "ThrowableNotThrown" )227    @Override228    public void run( IHookCallBack callBack, ITestResult testResult )229    {230        Method testMethod = testResult.getMethod().getConstructorOrMethod().getMethod();231        boolean beforeCallbacksExecuted = false;232        try233        {234            this.testContextManager.beforeTestExecution( this, testMethod );235            beforeCallbacksExecuted = true;236        }237        catch( Throwable ex )238        {239            this.testException = ex;240        }241        if( beforeCallbacksExecuted )242        {243            callBack.runTestMethod( testResult );244            this.testException = getTestResultException( testResult );245        }246        try247        {248            this.testContextManager.afterTestExecution( this, testMethod, this.testException );249        }250        catch( Throwable ex )251        {252            if( this.testException == null )253            {254                this.testException = ex;255            }256        }257        if( this.testException != null )258        {259            throwAsUncheckedException( this.testException );260        }261    }262    //endregion263    private Throwable getTestResultException( ITestResult testResult )264    {265        Throwable testResultException = testResult.getThrowable();266        if( testResultException instanceof InvocationTargetException )267        {268            testResultException = testResultException.getCause();269        }270        return testResultException;271    }272    @Nullable273    private RuntimeException throwAsUncheckedException( Throwable t )274    {275        throwAs( t );276        // Appeasing the compiler: the following line will never be executed.277        return null;278    }279    @SuppressWarnings( "unchecked" )280    private <T extends Throwable> void throwAs( Throwable t ) throws T281    {282        throw ( T ) t;283    }284}...Source:RulesListener.java  
1package BetaMax.BetaMaxSample.extension;2import java.lang.reflect.Field;3import java.util.ArrayList;4import java.util.Arrays;5import java.util.HashSet;6import java.util.List;7import java.util.Set;8import org.testng.IHookCallBack;9import org.testng.IHookable;10import org.testng.ITestContext;11import org.testng.ITestListener;12import org.testng.ITestNGMethod;13import org.testng.ITestResult;14public class RulesListener implements IHookable, ITestListener {15    private static interface Function0<T> {16        public void apply(T arg);17    }18    @Override19    public void run(IHookCallBack callBack, ITestResult testResult) {20        List<IHookable> hookables = getRules(testResult.getInstance(),21                IHookable.class);22        if (hookables.isEmpty()) {23            callBack.runTestMethod(testResult);24        } else {25            IHookable hookable = hookables.get(0);26            hookables.remove(0);27            for (IHookable iHookable : hookables) {28                hookable = compose(hookable, iHookable);29            }30            hookable.run(callBack, testResult);31        }32    }33    private IHookable compose(final IHookable first, final IHookable second) {34        return new IHookable() {35            @Override36            public void run(final IHookCallBack callBack,37                            final ITestResult testResult) {38                first.run(new IHookCallBack() {39                    @Override40                    public void runTestMethod(ITestResult testResult) {41                        second.run(callBack, testResult);42                    }43                    @Override44                    public Object[] getParameters() {45                        return callBack.getParameters();46                    }47                }, testResult);48            }49        };50    }51    private <T> List<T> getRules(Object object, Class<T> type) {52        List<T> rules = new ArrayList<T>();53        Field[] declaredFields = object.getClass().getFields();54        for (Field field : declaredFields) {55            NGRule annotation = field.getAnnotation(NGRule.class);56            if (annotation != null) {57                try {58                    Object fieldContent = field.get(object);59                    if (type.isAssignableFrom(field.getType())) {60                        @SuppressWarnings("unchecked")61                        T rule = (T) fieldContent;62                        rules.add(rule);63                    }64                } catch (Exception e) {65                    e.printStackTrace();66                }67            }68        }69        return rules;70    }71    @Override72    public void onTestStart(final ITestResult result) {73        executeRulesForInstance(new Function0<ITestListener>() {74            @Override75            public void apply(ITestListener listener) {76                listener.onTestStart(result);77            }78        }, result.getInstance());79    }80    @Override81    public void onTestSuccess(final ITestResult result) {82        executeRulesForInstance(new Function0<ITestListener>() {83            @Override84            public void apply(ITestListener listener) {85                listener.onTestSuccess(result);86            }87        }, result.getInstance());88    }89    @Override90    public void onTestFailure(final ITestResult result) {91        executeRulesForInstance(new Function0<ITestListener>() {92            @Override93            public void apply(ITestListener listener) {94                listener.onTestFailure(result);95            }96        }, result.getInstance());97    }98    @Override99    public void onTestSkipped(final ITestResult result) {100        executeRulesForInstance(new Function0<ITestListener>() {101            @Override102            public void apply(ITestListener listener) {103                listener.onTestSkipped(result);104            }105        }, result.getInstance());106    }107    @Override108    public void onTestFailedButWithinSuccessPercentage(final ITestResult result) {109        executeRulesForInstance(new Function0<ITestListener>() {110            @Override111            public void apply(ITestListener listener) {112                listener.onTestFailedButWithinSuccessPercentage(result);113            }114        }, result.getInstance());115    }116    @Override117    public void onStart(final ITestContext context) {118        executeRulesForContext(context,119                new Function0<ITestListener>() {120                    @Override121                    public void apply(ITestListener listener) {122                        listener.onStart(context);123                    }124                });125    }126    @Override127    public void onFinish(final ITestContext context) {128        executeRulesForContext(context, new Function0<ITestListener>() {129            @Override130            public void apply(ITestListener listener) {131                listener.onFinish(context);132            }133        });134    }135    private void executeRulesForContext(ITestContext context,136                                        Function0<ITestListener> action) {137        ITestNGMethod[] allTestMethods = context.getAllTestMethods();138        Set<Object> testInstances = new HashSet<Object>();139        for (ITestNGMethod iTestNGMethod : allTestMethods) {140            testInstances.addAll(Arrays.asList(iTestNGMethod.getInstances()));141        }142        for (Object instance : testInstances) {143            executeRulesForInstance(action, instance);144        }145    }146    private void executeRulesForInstance(Function0<ITestListener> action,147                                         Object allInst) {148        List<ITestListener> hookables = getRules(allInst, ITestListener.class);149        for (ITestListener listener : hookables) {150            action.apply(listener);151        }152    }153}...Source:AllureListener.java  
1package test.listener;2import io.qameta.allure.Attachment;3import org.openqa.selenium.OutputType;4import org.openqa.selenium.TakesScreenshot;5import org.openqa.selenium.WebDriver;6import org.testng.IHookCallBack;7import org.testng.IHookable;8import org.testng.ITestResult;9import test.common.BaseTest;10/**11 *  AllureListenerï¼çå¬ç¨ä¾çå¼å¸¸ï¼ç¨ä¾å¤±è´¥æªå¾12 *  IHookableï¼å®ç°è¿ä¸ªæ¥å£ï¼å½åçrunæ¹æ³å°ä¼æ¿æ¢ææµè¯ç±»éé¢ç@Testæ³¨è§£æ æ³¨çæµè¯æ¹æ³13 *  æµè¯ç¨ä¾å¤±è´¥æªå¾ï¼ææªå¾åµå
¥å°Allureæ¥è¡¨ä¸14 *  ï¼1ï¼å®ç°IHookableçå¬å¨ï¼éårunæ¹æ³ï¼çå¬ç¨ä¾çå¼å¸¸å¹¶æªå¾15 *  ï¼2ï¼éè¿Allure Attachement注解æ¥å®ç°éä»¶çåµå
¥16 */17public class AllureListener implements IHookable {18    @Override19    public void run(IHookCallBack iHookCallBack, ITestResult iTestResult) {20        // If a test class implements this interface, its run() method will be invoked instead of each @Test method found21        // ç¿»è¯çææï¼ä¸ä¸ªç±»æå»å®ç°implementsè¿ä¸ªæ¥å£çè¯ï¼é£ä¹å½åçrunæ¹æ³å°ä¼æ¿æ¢ææµè¯ç±»éé¢ç@Testæ³¨è§£æ æ³¨çæµè¯æ¹æ³22        // æ³è¦å¾å°æµè¯çç»æä¿¡æ¯23        // 1ãä¿è¯@Testæ³¨è§£æ æ³¨çæµè¯æ¹æ³è½å¤æ£å¸¸è¿è¡24        iHookCallBack.runTestMethod(iTestResult);25        // 2ã夿ç¨ä¾ç»ææ¯å¦æ£å¸¸26        if (iTestResult.getThrowable() != null) {27            // iTestResultåæ°æä¾äºAPI getInstance è·åå½åæµè¯ç±»çå®ä¾ï¼å¯¹è±¡ï¼28            BaseTest baseTest = (BaseTest) iTestResult.getInstance();29            // æ ¹æ®baseTestå¾å°driver30            WebDriver driver = baseTest.driver;31            // æªå¾å¹¶ææªå¾åµå
¥å°Allureæ¥è¡¨ä¸32            TakesScreenshot takesScreenshot = (TakesScreenshot) driver;33            // åæ°OutputTypeï¼æªå¾çç±»å34            byte[] screenShot = takesScreenshot.getScreenshotAs(OutputType.BYTES);35            saveScreenshot(screenShot);36        }37    }38    // @Attachment éä»¶39    // valueåæ°æ¯ä¸ºä½ çéä»¶çåå typeåæ°æ¯ä¸ºä½ çéä»¶ç±»å40    @Attachment(value = "Java screenshot", type = "image/png")41    public byte[] saveScreenshot(byte[] screenShot) {42        return screenShot;43    }44}...Source:AbstractDubbo.java  
1package com.zeratul;2import com.zeratul.base.TestBase;3import com.zeratul.dubbo.DubboService;4import com.zeratul.exception.ParameterException;5import org.testng.IHookCallBack;6import org.testng.IHookable;7import org.testng.ITestResult;8import org.testng.annotations.BeforeClass;9import java.util.Map;10import java.util.Optional;11import static com.zeratul.annotations.AnnotationUtils.isIgnoreAnnotation;12import static com.zeratul.util.ReflectionUtils.getInterfaceClass;13import static com.zeratul.util.TestngUtils.getParameters;14import static com.zeratul.util.TestngUtils.getTestMethod;15import static java.util.Optional.ofNullable;16/**17 * éç¨dubboæ¥å£æµè¯åºç±»18 * @author dreamyao19 * @version 1.020 *          Created by dreamyao on 2017/7/2.21 */22public abstract class AbstractDubbo<T> extends TestBase implements IHookable, ITestBase {23    private DubboService dubboService;24    @BeforeClass(alwaysRun = true)25    public void initEnv() {26        dubboService = new DubboService();27    }28    /**29     * æµè¯æ¹æ³æ¦æªå¨ãæææµè¯æ¹æ³å¨æ§è¡å¼å§ãæ§è¡ä¸ãæ§è¡å®æé½ä¼å¨æ¤æ¹æ³ä¸å®æ30     * @param callBack31     * @param testResult32     */33    @Override34    public void run(IHookCallBack callBack, ITestResult testResult) {35        // 妿æµè¯æ¹æ³ä¸æ@Ignore注解ï¼åè·³è¿æµè¯æ¡æ¶ç´æ¥æ§è¡æµè¯æ¹æ³36        if (isIgnoreAnnotation(getTestMethod(testResult))) {37            callBack.runTestMethod(testResult);38        }39    }40    @SuppressWarnings("unchecked")41    private void prepareTest(IHookCallBack callBack, ITestResult testResult) {42        Optional<Map<String, Object>> paramOptional = ofNullable(getParameters(testResult));43        Map<String, Object> param;44        if (paramOptional.isPresent()) {45            param = paramOptional.get();46        } else {47            throw new ParameterException("---------------è·åæµè¯å
¥å失败ï¼---------------");48        }49        Class<T> clazz = (Class<T>) getInterfaceClass(this);50    }51}...Source:TestResultListener.java  
1package com.lemon.listener;2import com.lemon.common.BaseTest;3import io.qameta.allure.Attachment;4import org.openqa.selenium.OutputType;5import org.openqa.selenium.TakesScreenshot;6import org.openqa.selenium.WebDriver;7import org.testng.IHookCallBack;8import org.testng.IHookable;9import org.testng.ITestResult;10import java.io.File;11/**12 * @author æªæªæ¬§å·´13 * @Description TODO14 * @date 2022/3/2 21:2815 * @Copyright æ¹åçé¶æª¬ä¿¡æ¯ææ¯æéå
¬å¸. All rights reserved.16 */17public class TestResultListener implements IHookable {18    //If a test class implements this interface, its run() method will be invoked instead of each @Test19    // * method found20    //ç¿»è¯è¿æ¥ï¼å¦æä¸ä¸ªç±»å®ç°äºè¿ä¸ªæ¥å£ï¼é£ä¹è¯¥æ¥å£çrunæ¹æ³å°ä¼ä»£æ¿@Testæ³¨è§£æ æ³¨çæµè¯æ¹æ³æ§è¡21    @Override22    public void run(IHookCallBack callBack, ITestResult testResult) {23        //让æµè¯æ¹æ³è½å¤æ£å¸¸çæ§è¡24        callBack.runTestMethod(testResult);25        //æ¶éå°æµè¯ç»ætestResult,夿testResultæ¯å¦æå¼å¸¸26        if(testResult.getThrowable() != null){27            //失败ç¨ä¾æªå¾28            //è·åå½åè¿è¡çæµè¯ç±»çå®ä¾ï¼å¯¹è±¡ï¼ï¼eg:AddCartTest29            BaseTest baseTest = (BaseTest) testResult.getInstance();30            TakesScreenshot takesScreenshot = (TakesScreenshot)baseTest.driver;31            byte[] screenshotDatas = takesScreenshot.getScreenshotAs(OutputType.BYTES);32            //å°æªå¾çæ°æ®ä¿åå°allureéä»¶ä¸33            add_to_allure(screenshotDatas);34        }35    }36    @Attachment37    public byte[] add_to_allure(byte[] datas){38        return datas;39    }40}...Source:ArezTestSupport.java  
1package arez.testng;2import arez.Arez;3import arez.ArezContext;4import arez.ArezTestUtil;5import arez.Disposable;6import arez.Function;7import arez.Observer;8import arez.Procedure;9import arez.SafeFunction;10import arez.SafeProcedure;11import javax.annotation.Nonnull;12import org.realityforge.braincheck.BrainCheckTestUtil;13import org.testng.IHookCallBack;14import org.testng.IHookable;15import org.testng.ITestResult;16import org.testng.annotations.AfterMethod;17import org.testng.annotations.BeforeMethod;18public interface ArezTestSupport19  extends IHookable20{21  @BeforeMethod22  default void preTest()23    throws Exception24  {25    BrainCheckTestUtil.resetConfig( false );26    ArezTestUtil.resetConfig( false );27  }28  @AfterMethod29  default void postTest()30  {31    ArezTestUtil.resetConfig( true );32    BrainCheckTestUtil.resetConfig( true );33  }34  @Override35  default void run( final IHookCallBack callBack, final ITestResult testResult )36  {37    new ArezTestHook().run( callBack, testResult );38  }39  @Nonnull40  default ArezContext context()41  {42    return Arez.context();43  }44  @Nonnull45  default Disposable pauseScheduler()46  {47    return context().pauseScheduler();48  }49  default void observer( @Nonnull final Procedure procedure )50  {51    context().observer( procedure, Observer.Flags.AREZ_OR_NO_DEPENDENCIES );52  }53  default void action( @Nonnull final Procedure action )54    throws Throwable55  {56    context().action( action );57  }58  default <T> T action( @Nonnull final Function<T> action )59    throws Throwable60  {61    return context().action( action );62  }63  default void safeAction( @Nonnull final SafeProcedure action )64  {65    context().safeAction( action );66  }67  default <T> T safeAction( @Nonnull final SafeFunction<T> action )68  {69    return context().safeAction( action );70  }71}...Source:IHookable.java  
1package org.testng;2/**3 * If a test class implements this interface, its run() method4 * will be invoked instead of each @Test method found.  The invocation of5 * the test method will then be performed upon invocation of the callBack()6 * method of the IHookCallBack parameter.7 *8 * This is useful to test classes that require JAAS authentication, which can9 * be implemented as follows:10 *11 * <pre>12 * public void run(final IHookCallBack icb, ITestResult testResult) {13 *   // Preferably initialized in a @Configuration method14 *   mySubject = authenticateWithJAAs();15 *16 *   Subject.doAs(mySubject, new PrivilegedExceptionAction() {17 *     public Object run() {18 *       icb.callback(testResult);19 *     }20 *   };21 * }22 * </pre>23 *24 * @author cbeust25 * Jan 28, 200626 */27public interface IHookable extends ITestNGListener {28  public void run(IHookCallBack callBack, ITestResult testResult);29}...Source:HookableListener.java  
1package listeners;2import org.testng.IHookCallBack;3import org.testng.IHookable;4import org.testng.ITestResult;5public class HookableListener implements IHookable {6    @Override7    public void run(IHookCallBack callBack, ITestResult testResult) {8        System.out.println("Execute this before any Test step is executed");9       callBack.runTestMethod(testResult);10    }11}12/*This interface skips the invocation of test methods and provides a run method which gets invoked instead of each @Test method found.13The test method is then invoked once the callBack() method of the IHookCallBack parameter is called.14 */15//It is utilized when you wish to perform testing on classes which require JAAS authentication. This can be used to set permissions, i.e.16// for whom the test method should run and when the test method should get skipped.*?The IHookable listener is...Interface IHookCallBack
Using AI Code Generation
1import org.testng.IHookCallBack;2import org.testng.IHookable;3import org.testng.ITestResult;4public class MyHookable implements IHookable {5    public void run(IHookCallBack callBack, ITestResult testResult) {6        System.out.println("before");7        callBack.runTestMethod(testResult);8        System.out.println("after");9    }10}11import org.testng.IHookCallBack;12import org.testng.IHookable;13import org.testng.ITestResult;14public class MyHookable implements IHookable {15    public void run(IHookCallBack callBack, ITestResult testResult) {16        System.out.println("before");17        callBack.runTestMethod(testResult);18        System.out.println("after");19    }20}21import org.testng.IHookCallBack;22import org.testng.IHookable;23import org.testng.ITestResult;24public class MyHookable implements IHookable {25    public void run(IHookCallBack callBack, ITestResult testResult) {26        System.out.println("before");27        callBack.runTestMethod(testResult);28        System.out.println("after");29    }30}31import org.testng.IHookCallBack;32import org.testng.IHookable;33import org.testng.ITestResult;34public class MyHookable implements IHookable {35    public void run(IHookCallBack callBack, ITestResult testResult) {36        System.out.println("before");37        callBack.runTestMethod(testResult);38        System.out.println("after");39    }40}41import org.testng.IHookCallBack;42import org.testng.IHookable;43import org.testng.ITestResult;44public class MyHookable implements IHookable {45    public void run(IHookCallBack callBack, ITestResult testResult) {46        System.out.println("before");47        callBack.runTestMethod(testResult);48        System.out.println("after");49    }50}51import org.testng.IHookCallBack;52import org.testng.IHookable;53import org.testng.ITestResult;54public class MyHookable implements IHookable {55    public void run(IHookCallBack callBack, ITestResult testResult) {56        System.out.println("before");57        callBack.runTestMethod(testResult);58        System.out.println("after");59    }60}Interface IHookCallBack
Using AI Code Generation
1import org.testng.IHookCallBack;2import org.testng.IHookable;3import org.testng.ITestResult;4import org.testng.annotations.Test;5public class TestClass implements IHookable {6	public void testMethod() {7		System.out.println("Test method");8	}9	public void run(IHookCallBack callBack, ITestResult testResult) {10		System.out.println("Run method");11		callBack.runTestMethod(testResult);12	}13}Interface IHookCallBack
Using AI Code Generation
1package com.test;2import org.testng.IHookCallBack;3import org.testng.IHookable;4import org.testng.ITestResult;5public class TestNG_IHookable implements IHookable {6    public void run(IHookCallBack callBack, ITestResult testResult) {7        System.out.println("IHookable is implemented");8        callBack.runTestMethod(testResult);9    }10}11package com.test;12import org.testng.annotations.Test;13public class TestNG_IHookable_Test {14    public void testMethod() {15        System.out.println("Test method running");16    }17}Interface IHookCallBack
Using AI Code Generation
1package testng;2import org.testng.IHookCallBack;3import org.testng.IHookable;4import org.testng.ITestResult;5public class Hookable implements IHookable {6	public void run(IHookCallBack callBack, ITestResult testResult) {7		System.out.println("Hello from Hookable");8		callBack.runTestMethod(testResult);9	}10}11package testng;12import org.testng.annotations.Test;13public class TestHookable {14	public void test1() {15		System.out.println("Hello from test1");16	}17}18package testng;19import org.testng.annotations.Test;20public class TestHookable implements IHookable {21	public void run(IHookCallBack callBack, ITestResult testResult) {22		System.out.println("Hello from Hookable");23		callBack.runTestMethod(testResult);24	}25}26package testng;27import org.testng.annotations.Test;28public class TestHookable {29	public void test1() {30		System.out.println("Hello from test1");31	}32}33package testng;34import org.testng.annotations.Test;35public class TestHookable implements IHookable {36	public void run(IHookCallBack callBack, ITestResult testResult) {37		System.out.println("Hello from Hookable");38		callBack.runTestMethod(testResult);39	}40}41package testng;42import org.testng.annotations.Test;43public class TestHookable {44	public void test1() {45		System.out.println("Hello from test1");46	}47}48package testng;49import org.testng.annotations.Test;50public class TestHookable implements IHookable {51	public void run(IHookCallBack callBack, ITestResult testResult) {52		System.out.println("Hello from Hookable");53		callBack.runTestMethod(testResult);54	}55}56package testng;57import org.testng.annotations.Test;58public class TestHookable {59	public void test1() {60		System.out.println("Hello from test1");61	}62}Interface IHookCallBack
Using AI Code Generation
1package mypackage;2import org.testng.IHookCallBack;3import org.testng.IHookable;4import org.testng.ITestResult;5import org.testng.annotations.Test;6public class TestNG_IHookable implements IHookable {7   public void testMethod() {8      System.out.println("TestNG_IHookable.testMethod()");9   }10   public void run(IHookCallBack callBack, ITestResult testResult) {11      System.out.println("TestNG_IHookable.run()");12      callBack.runTestMethod(testResult);13   }14}15TestNG_IHookable.run()16TestNG_IHookable.testMethod()Interface IHookCallBack
Using AI Code Generation
1package org.testng;2import org.testng.ITestResult;3import org.testng.ITestContext;4import org.testng.ITestListener;5import org.testng.ITestNGMethod;6public class TestNGListener implements ITestListener {7    public void onTestStart(ITestResult result) {8        System.out.println("Test Started");9    }10    public void onTestSuccess(ITestResult result) {11        System.out.println("Test Success");12    }13    public void onTestFailure(ITestResult result) {14        System.out.println("Test Failed");15    }16    public void onTestSkipped(ITestResult result) {17        System.out.println("Test Skipped");18    }19    public void onTestFailedButWithinSuccessPercentage(ITestResult result) {20        System.out.println("Test Failed But Within Success Percentage");21    }22    public void onStart(ITestContext context) {23        System.out.println("Test Started");24    }25    public void onFinish(ITestContext context) {26        System.out.println("Test Finished");27    }28}29package org.testng;30import org.testng.IHookCallBack;31import org.testng.IHookable;32import org.testng.ITestResult;33public class TestNGListener implements IHookable {34    public void run(IHookCallBack callBack, ITestResult testResult) {35        System.out.println("Test Started");36        callBack.runTestMethod(testResult);37        System.out.println("Test Finished");38    }39}40package org.testng;41import org.testng.IInvokedMethod;42import org.testng.IInvokedMethodListener;43import org.testng.ITestResult;44public class TestNGListener implements IInvokedMethodListener {45    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {46        System.out.println("Test Started");47    }48    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {49        System.out.println("Test Finished");50    }51}52package org.testng;53import org.testng.IInvokedMethod;54import org.testng.IInvokedMethodListener;55import org.testng.ITestResult;56public class TestNGListener implements IInvokedMethodListener {57    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {58        System.out.println("Test Started");59    }60    public void afterInvocation(IInterface IHookCallBack
Using AI Code Generation
1public class TestNGListener implements IHookCallBack, IHookable {2    public void run(IHookCallBack callBack, ITestResult testResult) {3        System.out.println("Before method " + testResult.getMethod().getMethodName());4        callBack.runTestMethod(testResult);5        System.out.println("After method " + testResult.getMethod().getMethodName());6    }7}8public class TestNGListener implements IHookable {9    public void run(IHookCallBack callBack, ITestResult testResult) {10        System.out.println("Before method " + testResult.getMethod().getMethodName());11        callBack.runTestMethod(testResult);12        System.out.println("After method " + testResult.getMethod().getMethodName());13    }14}15public class TestNGListener implements IHookCallBack {16    public void runTestMethod(ITestResult testResult) {17        System.out.println("Before method " + testResult.getMethod().getMethodName());18        testResult.setStatus(ITestResult.SUCCESS);19        System.out.println("After method " + testResult.getMethod().getMethodName());20    }21}22public class TestNGListener implements IHookCallBack {23    public void runTestMethod(ITestResult testResult) {24        System.out.println("Before method " + testResult.getMethod().getMethodName());25        testResult.setStatus(ITestResult.FAILURE);26        System.out.println("After method " + testResult.getMethod().getMethodName());27    }28}29public class TestNGListener implements IHookCallBack {30    public void runTestMethod(ITestResult testResult) {31        System.out.println("Before method " + testResult.getMethod().getMethodName());32        testResult.setStatus(ITestResult.SKIP);33        System.out.println("After method " + testResult.getMethod().getMethodName());34    }35}36public class TestNGListener implements IHookCallBack {37    public void runTestMethod(ITestResult testResult) {38        System.out.println("Before method " + testResult.getMethod().getMethodName());39        testResult.setStatus(ITestResult.STARTED);40        System.out.println("After method " + testResult.getMethod().getMethodName());Interface IHookCallBack
Using AI Code Generation
1public class TestNGListener implements IHookCallBack {2public void runTestMethod(ITestResult testResult) {3System.out.println("TestNGListener runTestMethod");4}5}6public class TestNGListener implements IHookable {7public void run(IHookCallBack callBack, ITestResult testResult) {8System.out.println("TestNGListener run");9}10}11public class TestNGListener implements IHookCallBack {12public void runTestMethod(ITestResult testResult) {13System.out.println("TestNGListener runTestMethod");14}15}16public class TestNGListener implements IHookable {17public void run(IHookCallBack callBack, ITestResult testResult) {18System.out.println("TestNGListener run");19}20}21public class TestNGListener implements IHookCallBack {22public void runTestMethod(ITestResult testResult) {23System.out.println("TestNGListener runTestMethod");24}25}26public class TestNGListener implements IHookable {27public void run(IHookCallBack callBack, ITestResult testResult) {28System.out.println("TestNGListener run");29}30}31public class TestNGListener implements IHookCallBack {32public void runTestMethod(ITestResult testResult) {33System.out.println("TestNGListener runTestMethod");34}35}36public class TestNGListener implements IHookable {37public void run(IHookCallBack callBack, ITestResult testResult) {38System.out.println("TestNGListener run");39}40}41public class TestNGListener implements IHookCallBack {42public void runTestMethod(ITestResult testResult) {43System.out.println("TestNGListener runTestMethod");44}45}46import org.testng.IHookable;47import org.testng.ITestResult;48public class TestNGListener implements IHookable {49    public void run(IHookCallBack callBack, ITestResult testResult) {50        System.out.println("Test Started");51        callBack.runTestMethod(testResult);52        System.out.println("Test Finished");53    }54}55package org.testng;56import org.testng.IInvokedMethod;57import org.testng.IInvokedMethodListener;58import org.testng.ITestResult;59public class TestNGListener implements IInvokedMethodListener {60    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {61        System.out.println("Test Started");62    }63    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {64        System.out.println("Test Finished");65    }66}67package org.testng;68import org.testng.IInvokedMethod;69import org.testng.IInvokedMethodListener;70import org.testng.ITestResult;71public class TestNGListener implements IInvokedMethodListener {72    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {73        System.out.println("Test Started");74    }75    public void afterInvocation(IInterface IHookCallBack
Using AI Code Generation
1public class TestNGListener implements IHookCallBack, IHookable {2    public void run(IHookCallBack callBack, ITestResult testResult) {3        System.out.println("Before method " + testResult.getMethod().getMethodName());4        callBack.runTestMethod(testResult);5        System.out.println("After method " + testResult.getMethod().getMethodName());6    }7}8public class TestNGListener implements IHookable {9    public void run(IHookCallBack callBack, ITestResult testResult) {10        System.out.println("Before method " + testResult.getMethod().getMethodName());11        callBack.runTestMethod(testResult);12        System.out.println("After method " + testResult.getMethod().getMethodName());13    }14}15public class TestNGListener implements IHookCallBack {16    public void runTestMethod(ITestResult testResult) {17        System.out.println("Before method " + testResult.getMethod().getMethodName());18        testResult.setStatus(ITestResult.SUCCESS);19        System.out.println("After method " + testResult.getMethod().getMethodName());20    }21}22public class TestNGListener implements IHookCallBack {23    public void runTestMethod(ITestResult testResult) {24        System.out.println("Before method " + testResult.getMethod().getMethodName());25        testResult.setStatus(ITestResult.FAILURE);26        System.out.println("After method " + testResult.getMethod().getMethodName());27    }28}29public class TestNGListener implements IHookCallBack {30    public void runTestMethod(ITestResult testResult) {31        System.out.println("Before method " + testResult.getMethod().getMethodName());32        testResult.setStatus(ITestResult.SKIP);33        System.out.println("After method " + testResult.getMethod().getMethodName());34    }35}36public class TestNGListener implements IHookCallBack {37    public void runTestMethod(ITestResult testResult) {38        System.out.println("Before method " + testResult.getMethod().getMethodName());39        testResult.setStatus(ITestResult.STARTED);40        System.out.println("After method " + testResult.getMethod().getMethodName());Interface IHookCallBack
Using AI Code Generation
1public class TestNGListener implements IHookCallBack {2public void runTestMethod(ITestResult testResult) {3System.out.println("TestNGListener runTestMethod");4}5}6public class TestNGListener implements IHookable {7public void run(IHookCallBack callBack, ITestResult testResult) {8System.out.println("TestNGListener run");9}10}11public class TestNGListener implements IHookCallBack {12public void runTestMethod(ITestResult testResult) {13System.out.println("TestNGListener runTestMethod");14}15}16public class TestNGListener implements IHookable {17public void run(IHookCallBack callBack, ITestResult testResult) {18System.out.println("TestNGListener run");19}20}21public class TestNGListener implements IHookCallBack {22public void runTestMethod(ITestResult testResult) {23System.out.println("TestNGListener runTestMethod");24}25}26public class TestNGListener implements IHookable {27public void run(IHookCallBack callBack, ITestResult testResult) {28System.out.println("TestNGListener run");29}30}31public class TestNGListener implements IHookCallBack {32public void runTestMethod(ITestResult testResult) {33System.out.println("TestNGListener runTestMethod");34}35}36public class TestNGListener implements IHookable {37public void run(IHookCallBack callBack, ITestResult testResult) {38System.out.println("TestNGListener run");39}40}41public class TestNGListener implements IHookCallBack {42public void runTestMethod(ITestResult testResult) {43System.out.println("TestNGListener runTestMethod");44}45}46package testng;47import org.testng.annotations.Test;48public class TestHookable implements IHookable {49	public void run(IHookCallBack callBack, ITestResult testResult) {50		System.out.println("Hello from Hookable");51		callBack.runTestMethod(testResult);52	}53}54package testng;55import org.testng.annotations.Test;56public class TestHookable {57	public void test1() {58		System.out.println("Hello from test1");59	}60}61package testng;62import org.testng.annotations.Test;63public class TestHookable implements IHookable {64	public void run(IHookCallBack callBack, ITestResult testResult) {65		System.out.println("Hello from Hookable");66		callBack.runTestMethod(testResult);67	}68}69package testng;70import org.testng.annotations.Test;71public class TestHookable {72	public void test1() {73		System.out.println("Hello from test1");74	}75}Interface IHookCallBack
Using AI Code Generation
1public class TestNGListener implements IHookCallBack, IHookable {2    public void run(IHookCallBack callBack, ITestResult testResult) {3        System.out.println("Before method " + testResult.getMethod().getMethodName());4        callBack.runTestMethod(testResult);5        System.out.println("After method " + testResult.getMethod().getMethodName());6    }7}8public class TestNGListener implements IHookable {9    public void run(IHookCallBack callBack, ITestResult testResult) {10        System.out.println("Before method " + testResult.getMethod().getMethodName());11        callBack.runTestMethod(testResult);12        System.out.println("After method " + testResult.getMethod().getMethodName());13    }14}15public class TestNGListener implements IHookCallBack {16    public void runTestMethod(ITestResult testResult) {17        System.out.println("Before method " + testResult.getMethod().getMethodName());18        testResult.setStatus(ITestResult.SUCCESS);19        System.out.println("After method " + testResult.getMethod().getMethodName());20    }21}22public class TestNGListener implements IHookCallBack {23    public void runTestMethod(ITestResult testResult) {24        System.out.println("Before method " + testResult.getMethod().getMethodName());25        testResult.setStatus(ITestResult.FAILURE);26        System.out.println("After method " + testResult.getMethod().getMethodName());27    }28}29public class TestNGListener implements IHookCallBack {30    public void runTestMethod(ITestResult testResult) {31        System.out.println("Before method " + testResult.getMethod().getMethodName());32        testResult.setStatus(ITestResult.SKIP);33        System.out.println("After method " + testResult.getMethod().getMethodName());34    }35}36public class TestNGListener implements IHookCallBack {37    public void runTestMethod(ITestResult testResult) {38        System.out.println("Before method " + testResult.getMethod().getMethodName());39        testResult.setStatus(ITestResult.STARTED);40        System.out.println("After method " + testResult.getMethod().getMethodName());Interface IHookCallBack
Using AI Code Generation
1public class TestNGListener implements IHookCallBack {2public void runTestMethod(ITestResult testResult) {3System.out.println("TestNGListener runTestMethod");4}5}6public class TestNGListener implements IHookable {7public void run(IHookCallBack callBack, ITestResult testResult) {8System.out.println("TestNGListener run");9}10}11public class TestNGListener implements IHookCallBack {12public void runTestMethod(ITestResult testResult) {13System.out.println("TestNGListener runTestMethod");14}15}16public class TestNGListener implements IHookable {17public void run(IHookCallBack callBack, ITestResult testResult) {18System.out.println("TestNGListener run");19}20}21public class TestNGListener implements IHookCallBack {22public void runTestMethod(ITestResult testResult) {23System.out.println("TestNGListener runTestMethod");24}25}26public class TestNGListener implements IHookable {27public void run(IHookCallBack callBack, ITestResult testResult) {28System.out.println("TestNGListener run");29}30}31public class TestNGListener implements IHookCallBack {32public void runTestMethod(ITestResult testResult) {33System.out.println("TestNGListener runTestMethod");34}35}36public class TestNGListener implements IHookable {37public void run(IHookCallBack callBack, ITestResult testResult) {38System.out.println("TestNGListener run");39}40}41public class TestNGListener implements IHookCallBack {42public void runTestMethod(ITestResult testResult) {43System.out.println("TestNGListener runTestMethod");44}45}TestNG is a Java-based open-source framework for test automation that includes various test types, such as unit testing, functional testing, E2E testing, etc. TestNG is in many ways similar to JUnit and NUnit. But in contrast to its competitors, its extensive features make it a lot more reliable framework. One of the major reasons for its popularity is its ability to structure tests and improve the scripts' readability and maintainability. Another reason can be the important characteristics like the convenience of using multiple annotations, reliance, and priority that make this framework popular among developers and testers for test design. You can refer to the TestNG tutorial to learn why you should choose the TestNG framework.
You can push your abilities to do automated testing using TestNG and advance your career by earning a TestNG certification. Check out our TestNG certification.
Watch this complete tutorial to learn how you can leverage the capabilities of the TestNG framework for Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
