How to use Interface IHookable class of org.testng package

Best Testng code snippet using org.testng.Interface IHookable

Run Testng automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package BetaMax.BetaMaxSample.extension;
2
3import java.lang.reflect.Field;
4import java.util.ArrayList;
5import java.util.Arrays;
6import java.util.HashSet;
7import java.util.List;
8import java.util.Set;
9
10import org.testng.IHookCallBack;
11import org.testng.IHookable;
12import org.testng.ITestContext;
13import org.testng.ITestListener;
14import org.testng.ITestNGMethod;
15import org.testng.ITestResult;
16
17public class RulesListener implements IHookable, ITestListener {
18
19    private static interface Function0<T> {
20        public void apply(T arg);
21    }
22
23    @Override
24    public void run(IHookCallBack callBack, ITestResult testResult) {
25        List<IHookable> hookables = getRules(testResult.getInstance(),
26                IHookable.class);
27        if (hookables.isEmpty()) {
28            callBack.runTestMethod(testResult);
29        } else {
30            IHookable hookable = hookables.get(0);
31            hookables.remove(0);
32            for (IHookable iHookable : hookables) {
33                hookable = compose(hookable, iHookable);
34            }
35            hookable.run(callBack, testResult);
36        }
37    }
38
39    private IHookable compose(final IHookable first, final IHookable second) {
40        return new IHookable() {
41
42            @Override
43            public void run(final IHookCallBack callBack,
44                            final ITestResult testResult) {
45                first.run(new IHookCallBack() {
46
47                    @Override
48                    public void runTestMethod(ITestResult testResult) {
49                        second.run(callBack, testResult);
50                    }
51
52                    @Override
53                    public Object[] getParameters() {
54                        return callBack.getParameters();
55                    }
56                }, testResult);
57            }
58        };
59    }
60
61    private <T> List<T> getRules(Object object, Class<T> type) {
62        List<T> rules = new ArrayList<T>();
63        Field[] declaredFields = object.getClass().getFields();
64        for (Field field : declaredFields) {
65            NGRule annotation = field.getAnnotation(NGRule.class);
66            if (annotation != null) {
67                try {
68                    Object fieldContent = field.get(object);
69                    if (type.isAssignableFrom(field.getType())) {
70                        @SuppressWarnings("unchecked")
71                        T rule = (T) fieldContent;
72                        rules.add(rule);
73                    }
74                } catch (Exception e) {
75                    e.printStackTrace();
76                }
77            }
78        }
79        return rules;
80    }
81
82    @Override
83    public void onTestStart(final ITestResult result) {
84        executeRulesForInstance(new Function0<ITestListener>() {
85            @Override
86            public void apply(ITestListener listener) {
87                listener.onTestStart(result);
88            }
89        }, result.getInstance());
90    }
91
92    @Override
93    public void onTestSuccess(final ITestResult result) {
94        executeRulesForInstance(new Function0<ITestListener>() {
95            @Override
96            public void apply(ITestListener listener) {
97                listener.onTestSuccess(result);
98            }
99        }, result.getInstance());
100    }
101
102    @Override
103    public void onTestFailure(final ITestResult result) {
104        executeRulesForInstance(new Function0<ITestListener>() {
105            @Override
106            public void apply(ITestListener listener) {
107                listener.onTestFailure(result);
108            }
109        }, result.getInstance());
110    }
111
112    @Override
113    public void onTestSkipped(final ITestResult result) {
114        executeRulesForInstance(new Function0<ITestListener>() {
115            @Override
116            public void apply(ITestListener listener) {
117                listener.onTestSkipped(result);
118            }
119        }, result.getInstance());
120    }
121
122    @Override
123    public void onTestFailedButWithinSuccessPercentage(final ITestResult result) {
124        executeRulesForInstance(new Function0<ITestListener>() {
125            @Override
126            public void apply(ITestListener listener) {
127                listener.onTestFailedButWithinSuccessPercentage(result);
128            }
129        }, result.getInstance());
130    }
131
132    @Override
133    public void onStart(final ITestContext context) {
134        executeRulesForContext(context,
135                new Function0<ITestListener>() {
136                    @Override
137                    public void apply(ITestListener listener) {
138                        listener.onStart(context);
139                    }
140                });
141    }
142
143    @Override
144    public void onFinish(final ITestContext context) {
145        executeRulesForContext(context, new Function0<ITestListener>() {
146            @Override
147            public void apply(ITestListener listener) {
148                listener.onFinish(context);
149            }
150        });
151    }
152
153    private void executeRulesForContext(ITestContext context,
154                                        Function0<ITestListener> action) {
155        ITestNGMethod[] allTestMethods = context.getAllTestMethods();
156        Set<Object> testInstances = new HashSet<Object>();
157        for (ITestNGMethod iTestNGMethod : allTestMethods) {
158            testInstances.addAll(Arrays.asList(iTestNGMethod.getInstances()));
159        }
160        for (Object instance : testInstances) {
161            executeRulesForInstance(action, instance);
162        }
163    }
164
165    private void executeRulesForInstance(Function0<ITestListener> action,
166                                         Object allInst) {
167        List<ITestListener> hookables = getRules(allInst, ITestListener.class);
168        for (ITestListener listener : hookables) {
169            action.apply(listener);
170        }
171    }
172}
Full Screen
copy
1package arez.testng;
2
3import arez.Arez;
4import arez.ArezContext;
5import arez.ArezTestUtil;
6import arez.Disposable;
7import arez.Function;
8import arez.Observer;
9import arez.Procedure;
10import arez.SafeFunction;
11import arez.SafeProcedure;
12import javax.annotation.Nonnull;
13import org.realityforge.braincheck.BrainCheckTestUtil;
14import org.testng.IHookCallBack;
15import org.testng.IHookable;
16import org.testng.ITestResult;
17import org.testng.annotations.AfterMethod;
18import org.testng.annotations.BeforeMethod;
19
20public interface ArezTestSupport
21  extends IHookable
22{
23  @BeforeMethod
24  default void preTest()
25    throws Exception
26  {
27    BrainCheckTestUtil.resetConfig( false );
28    ArezTestUtil.resetConfig( false );
29  }
30
31  @AfterMethod
32  default void postTest()
33  {
34    ArezTestUtil.resetConfig( true );
35    BrainCheckTestUtil.resetConfig( true );
36  }
37
38  @Override
39  default void run( final IHookCallBack callBack, final ITestResult testResult )
40  {
41    new ArezTestHook().run( callBack, testResult );
42  }
43
44  @Nonnull
45  default ArezContext context()
46  {
47    return Arez.context();
48  }
49
50  @Nonnull
51  default Disposable pauseScheduler()
52  {
53    return context().pauseScheduler();
54  }
55
56  default void observer( @Nonnull final Procedure procedure )
57  {
58    context().observer( procedure, Observer.Flags.AREZ_OR_NO_DEPENDENCIES );
59  }
60
61  default void action( @Nonnull final Procedure action )
62    throws Throwable
63  {
64    context().action( action );
65  }
66
67  default <T> T action( @Nonnull final Function<T> action )
68    throws Throwable
69  {
70    return context().action( action );
71  }
72
73  default void safeAction( @Nonnull final SafeProcedure action )
74  {
75    context().safeAction( action );
76  }
77
78  default <T> T safeAction( @Nonnull final SafeFunction<T> action )
79  {
80    return context().safeAction( action );
81  }
82}
83
Full Screen
copy
1import org.testng.IHookCallBack;
2import org.testng.IHookable;
3import org.testng.ITestResult;
4import org.testng.annotations.DataProvider;
5import org.testng.annotations.Test;
6
7import java.time.DayOfWeek;
8
9public class TestNgPlayground implements IHookable {
10
11    private static final DayOfWeek SOME_CONST = DayOfWeek.TUESDAY;
12
13    @DataProvider
14    public Object[][] getStuff() {
15        return new Object[][]{
16                {"param1", DayOfWeek.MONDAY},    // Skip this
17                {"param2", DayOfWeek.TUESDAY},  // Run this
18                {"param3", DayOfWeek.WEDNESDAY} // Skip this
19        };
20    }
21
22    @Test(dataProvider = "getStuff")
23    public void testt(String param1, DayOfWeek param2) {
24        System.err.println("[" + param1 + ", " + param2 + "]");
25    }
26
27    @Override
28    public void run(IHookCallBack callBack, ITestResult testResult) {
29        Object[] parameters = callBack.getParameters();
30        DayOfWeek dataProviderValue = (DayOfWeek) parameters[1];
31        if (dataProviderValue != SOME_CONST) {
32            callBack.runTestMethod(testResult);
33        } else {
34            testResult.setStatus(ITestResult.SKIP);
35        }
36    }
37}
38
Full Screen
copy
1[param1, MONDAY]
2[param3, WEDNESDAY]
3
4Test ignored.
5
6===============================================
7Default Suite
8Total tests run: 3, Failures: 0, Skips: 1
9===============================================
10
Full Screen
copy
1import java.lang.annotation.Retention;
2import java.lang.annotation.Target;
3
4import static java.lang.annotation.ElementType.METHOD;
5import static java.lang.annotation.ElementType.TYPE;
6
7@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
8@Target({METHOD, TYPE})
9public @interface InjectParameters {
10  String url() default "";
11
12  String getComplexClass() default "testngImplementation.acomplexclass";
13}
14
Full Screen
copy
1import org.testng.IHookCallBack;
2import org.testng.IHookable;
3import org.testng.ITestResult;
4import org.testng.internal.ClassHelper;
5
6import java.util.ArrayList;
7import java.util.List;
8
9public class AbstractValidator implements IHookable {
10
11  public AbstractValidator() {
12    // more common setups reports, selenium, utilities, etc...
13  }
14
15  public void setup() {}
16
17  public void tearDown() {}
18
19  @Override
20  public void run(IHookCallBack callBack, ITestResult testResult) {
21    System.out.println("We made it to run on the Abstract Validator 2");
22    setup();
23    Object[] parameters = callBack.getParameters();
24    Object[] injected = getParametersToInject(testResult);
25    if (parameters.length == injected.length) {
26      System.arraycopy(injected, 0, parameters, 0, parameters.length);
27    }
28    callBack.runTestMethod(testResult);
29    tearDown();
30  }
31
32  private Object[] getParametersToInject(ITestResult testResult) {
33    List<Object> parameters = new ArrayList<>();
34    InjectParameters toInject =
35        testResult
36            .getMethod()
37            .getConstructorOrMethod()
38            .getMethod()
39            .getAnnotation(InjectParameters.class);
40    if (toInject != null) {
41      parameters.add(toInject.url());
42      parameters.add(ClassHelper.newInstance(ClassHelper.forName(toInject.getComplexClass())));
43    }
44    return parameters.toArray(new Object[0]);
45  }
46}
47
Full Screen
copy
1public class TestCreation extends AbstractValidator {
2  @Test
3  @InjectParameters(url = "https://www.google.com/")
4  // The @Parameters is being used just as a place holder here. To prevent TestNG from triggering
5  // Validations saying that parameter required but not provided. I think this would be fixed
6  // as part of fix for https://github.com/cbeust/testng/issues/564 which would be available in
7  // TestNG 7.0.0
8
9  @Parameters({"url", "a"})
10  public void sampletest2google(@Optional String url, @Optional acomplexclass a) {
11    System.err.println("URL is " + url);
12    System.err.println("Complex object  is " + a.toString());
13  }
14
15  @Test
16  @InjectParameters(url = "https://www.bing.com/")
17  @Parameters({"url", "a"})
18  public void sampletest3bing(@Optional String url, @Optional acomplexclass a) {
19    System.err.println("URL is " + url);
20    System.err.println("Complex object  is " + a.toString());
21  }
22}
23
Full Screen
copy
1public class TestNg
2{
3    private WebDriver driver;
4
5    @Test(dataProvider = "getData")
6    public void test(String url, String title)
7    {
8        driver.navigate().to(url);
9        assertEquals(driver.getTitle(), title, "Verify title");
10    }
11
12    @BeforeMethod
13    public void setup()
14    {
15        String chromeDriverPath = "C:\\path\\to\\chromedriver.exe";
16        System.setProperty("webdriver.chrome.driver", chromeDriverPath);
17        driver = new ChromeDriver();
18    }
19
20    @AfterMethod
21    public void tearDown()
22    {
23        driver.close();
24        driver.quit();
25    }
26
27    @DataProvider
28    public Object[][] getData()
29    {
30        return new Object[][] { { "http://www.google.com", "Google" }, { "http://www.bing.com", "Bing" } };
31    }
32}
33
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in Interface-IHookable

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)