Issue
I need somehow to intercept Test class constructor to override a behavior. In JUnit
, it is done with:
@Override
public <T> T interceptTestClassConstructor(Invocation<T> invocation,
ReflectiveInvocationContext<Constructor<T>> invocationContext,
ExtensionContext extensionContext) throws Throwable {
...
}
How is this achievable in TestNG?
Solution
You could override the behavior using IObjectFactory
.
public class CustomObjectFactory implements IObjectFactory {
@Override
public Object newInstance(Constructor constructor, Object... params) {
if(constructor.getDeclaringClass().equals(YourTestCalss.class)) {
return yourCustomObject();
}
try {
return constructor.newInstance(params);
} catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// error handling...
}
return null; // or any other object or throw exception
}
}
Now in a test class, add a method as below:
@Test
public class YourTestClass {
// ......
// test methods
// ......
@ObjectFactory
public ITestObjectFactory getObjectFactory() {
return new CustomObjectFactory();
}
}
Please note that even though this method is declared inside YourTestClass
, this same object factory would be used for every other test class in your suite. Hence the if
condition to check the class is required in CustomObjectFactory.newInstance
.
You may also try IObjectFactory2
which has a newInstance
method taking Class
as the parameter.
TestNG has an implementation for IObjectFactory
-> ObjectFactoryImpl
.
You could use extends ObjectFactoryImpl
instead, in which case the code within the `newInstance could be:
if(constructor.getDeclaringClass().equals(YourTestCalss.class)) {
return yourCustomObject();
}
return super.newInstance(constructor, params);
BUT note that, Since ObjectFactoryImpl
is inside the testng.internal
package, I assume that extending ObjectFactoryImpl
is not recommended.
Answered By - Gautham M