TestNG拦截TestClassConstructor模拟

TestNG interceptTestClassConstructor analog

我需要以某种方式拦截 Test class 构造函数以覆盖行为。在 JUnit 中,它是通过以下方式完成的:

@Override
public <T> T interceptTestClassConstructor(Invocation<T> invocation,
                                           ReflectiveInvocationContext<Constructor<T>> invocationContext,
                                           ExtensionContext extensionContext) throws Throwable {
...
}

这在 TestNG 中是如何实现的?

正如 mailing group, @KrishnanMahadevan fixed a bug 中所讨论的,这将允许在 7.5 版

中拦截 Test class 构造函数
public class LocalSuiteAlteringListener implements IAlterSuiteListener {
@Override
public void alter(List<XmlSuite> suites) {
   suites.forEach(each -> each.setObjectFactoryClass(MyFactory.class));

您可以使用 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
    }
}

现在在测试中class,添加如下方法:

@Test
public class YourTestClass {
    // ......
    // test methods
    // ......


    @ObjectFactory
    public ITestObjectFactory getObjectFactory() {
        return new CustomObjectFactory();
    }
}

请注意,即使此方法是在 YourTestClass 中声明的,这个相同的对象工厂也会用于您套件中的所有其他测试 class。因此 CustomObjectFactory.newInstance.

中需要检查 class 的 if 条件

您也可以试试 IObjectFactory2,它有一个以 Class 作为参数的 newInstance 方法。


TestNG 有 IObjectFactory -> ObjectFactoryImpl 的实现。 您可以改用 extends ObjectFactoryImpl,在这种情况下,`newInstance 中的代码可以是:

if(constructor.getDeclaringClass().equals(YourTestCalss.class)) {
    return yourCustomObject();
}
return super.newInstance(constructor, params);

但请注意,由于 ObjectFactoryImpltestng.internal 包内,我认为不建议扩展 ObjectFactoryImpl