1.8. Example of IHookable

1.8. Example of IHookable


If a test class wants to do something more, like a JAAS authentication, before invoking the test method, it needs to implement IHookable. If a test class implements this interface, its run() method will be invoked instead of each @Testmethod found.
The test method being invoked is passed in, encapsulated in a IHookCallBack object so one can run it by invokingIHookCallBack.runTestMethod().
In the below example, we will skip running the test, based on the test method’s parameter value. If the parameter value is “local” environment, the test is skipped but run for other valid environments.
HookableExample

HookableExample
package com.iHookable;
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class HookableExample implements IHookable {
@Override
public void run(IHookCallBack callBack, ITestResult testResult) {
Object[] parms = callBack.getParameters();
if (parms[0].equals("local")) {
System.out.println("Skipping for parameter local");
} else {
callBack.runTestMethod(testResult);
}
}
@BeforeSuite
public void beforeSuite() {
System.out.println("before suite");
}
@Test(dataProvider="getDp")
public void testcase1(String p) {
System.out.println("test method testcase1 called with parameter " + p);
}
@DataProvider
public Object[][] getDp() {
return new Object[][]{{"staging"}, {"production"}, {"local"}};
}
}
hookableTestNg.xml
<?xml version="1.0" encoding="UTF-8"?>
<suite name="HookableExample Suite">
<test name="HookableListenerExample">
<classes>
<class name="com.iHookable.HookableExample" />
</classes>
</test>
</suite>
Output :
[TestNGContentHandler] [WARN] It is strongly recommended to add "<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >" at the top of your file, otherwise TestNG may fail or not work as expected.
[TestNG] Running:
before suite
test method testcase1 called with parameter staging
test method testcase1 called with parameter production
Skipping for parameter local
===============================================
HookableExample Suite
Total tests run: 3, Failures: 0, Skips: 0
===============================================
view raw 3.output.txt hosted with ❤ by GitHub

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.