gpt4 book ai didi

java - 与@BeforeClass 等效的 TestNG 监听器,可以访问上下文

转载 作者:行者123 更新时间:2023-12-03 18:25:23 26 4
gpt4 key购买 nike

我花了几天时间寻找一种方法,将我的一个 @BeforeClass 方法移动到监听器类,我可以在 xml 中引用我定义内容操作系统测试套件的地方。

我面临的问题是我将 Spring 用于 DI,并且在 @BeforeClass 方法中我向 testng 上下文添加了一些属性,因此我可以在其他地方使用它们(其他监听器) .

我尝试使用 ITestListener 中的 onStart(final ITestContext context)。但是那个方法似乎是在 spring 设法创建 bean 之前调用的,我无法执行我的操作,因为我所有的 bean 都是 null。

我尝试使用 IClassListener 中的 onBeforeClass(ITestClass testClass)。但是那个方法只提供了 ITestClass,它不给我访问上下文的权限,所以我不能设置我的属性。

现在我正在试验来自 IConfigurationListeneronConfigurationSuccess(final ITestResult itr),但这需要使用 if 语句仅当配置方法名称等于时才运行我的代码springTestContextPrepareTestInstance

有谁知道更好的方法吗?

[编辑] 代码示例

@Component
public class CleanupHelper {

private static SomeBean someBean;

@Autowired
public CleanupHelper(SomeBean someBean){
CleanupHelper.someBean = someBean;
}

public static Object getSomething(){
return someBean.getSomething();
}
}
public class ExcludedGroupsListener implements IConfigurationListener {

@Override
public void onConfigurationSuccess(final ITestResult itr) {
if (itr.getName().contains("springTestContextPrepareTestInstance")) {
var something = CleanupHelper.getSomething();
if (something != null && someOtherCondition) {

itr.setAttribute("someObject", something);
}
}
}
}

@ContextConfiguration(classes = TestConfig.class)
public class SomeTests extends AbstractTestNGSpringContextTests {

@Test
public void someTest(){
// doSomething
}

}
@Configuration
@ComponentScan(basePackages = "com.some",
excludeFilters = @Filter(type = FilterType.REGEX, pattern = "com.some.else..*"))
public class TestConfig {
}

上面的代码有效...不幸的是 onConfigurationSuccess 方法在每个配置方法之后被调用。

最佳答案

试试Annotation Transformers .

您可以像添加任何其他监听器一样将其添加到您的 testng.xml 中。

在那里你可以做这样的事情:

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;

public class TestAnnotationTransformer implements IAnnotationTransformer {

@SuppressWarnings("rawtypes")
@Override
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {

if (testMethod.getName().equals("MyTest1"))
annotation.setGroups( new String[] {"GroupA" });

if(ignoreTestDependencies)
annotation.setIgnoreMissingDependencies(true);

}

}

只是一个例子,但你有很多东西可以玩。

请记住,正如我在评论中所述,它在运行时之前 运行,因此您无法像使用普通监听器那样随时更改内容。

关于java - 与@BeforeClass 等效的 TestNG 监听器,可以访问上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524319/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com