Java 我可以管理@DataProvider在@BeforeMethod之后运行吗
在@Test方法上方,我有一个注释,其中包含@DataProvider应该从中提取数据的文件名。我尝试在@BeforeMethod中初始化该文件,但没有成功,因为@BeforeMethod在@DataProvider之后运行 我需要在@BeforeMethod中初始化文件的原因是,我只能从该方法知道运行了哪个@Test方法,然后使用文件名提取其注释。另外,我希望在每个@Test方法运行之前都这样做。我怎样才能让这东西工作Java 我可以管理@DataProvider在@BeforeMethod之后运行吗,java,testng,Java,Testng,在@Test方法上方,我有一个注释,其中包含@DataProvider应该从中提取数据的文件名。我尝试在@BeforeMethod中初始化该文件,但没有成功,因为@BeforeMethod在@DataProvider之后运行 我需要在@BeforeMethod中初始化文件的原因是,我只能从该方法知道运行了哪个@Test方法,然后使用文件名提取其注释。另外,我希望在每个@Test方法运行之前都这样做。我怎样才能让这东西工作 String fileName; @MyAnnotation(fileN
String fileName;
@MyAnnotation(fileName="abc.txt")
@Test(dataProvider = "getData")
public void test(DataFromFile data) {
...showData();
}
@BeforeMethod
public void beforeMethod(Method invokingMethod) {
fileName ... = invokingMethod.getAnnotation(MyAnnotation.class).fileName();
}
@DataProvider
public Object[][] getData() {
... initialize new File(fileName);
...
}
你也许应该这样做
package com.rationaleemotions.stackoverflow;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import static java.lang.annotation.ElementType.METHOD;
public class DataProviderGames {
@Test(dataProvider = "getData")
@MyAnnotation(fileName = "input.txt")
public void test(String data) {
System.err.println("Test data :" + data);
}
@Test(dataProvider = "getData")
@MyAnnotation(fileName = "input.csv")
public void anotherTest(String data) {
System.err.println("Test data :" + data);
}
@DataProvider
public Object[][] getData(Method method) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
return new Object[][]{
{annotation.fileName()}
};
}
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({METHOD})
@interface MyAnnotation {
String fileName() default "";
}
}
由于TestNG为您提供了注入实际“方法”的功能,调用了
@DataProvider
注释方法,因此您应该能够直接使用反射来查询方法参数的注释,并通过它检索文件名。有多少@MyAnnotation(fileName=“abc.txt”)
带注释的方法在此类中?一。这对问题有何影响?