【问题标题】:Can I manage @DataProvider to run after @BeforeMethod我可以管理@DataProvider 在@BeforeMethod 之后运行吗
【发布时间】:2017-03-19 12:32:45
【问题描述】:

在我的@Test 方法之上,我有一个注释,其中包含@DataProvider 应该从中提取数据的文件名。我尝试在@BeforeMethod 中初始化该文件,但我没有成功,因为@BeforeMethod 运行AFTER @DataProvider。

我需要在 @BeforeMethod 中初始化 File 的原因是我只能从该方法中知道运行了哪个 @Test 方法,然后使用文件名提取其注释。另外,我想在每个 @Test 方法运行之前执行它。我怎样才能使这件事起作用?

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);
    ... 
}

【问题讨论】:

  • 这个类中有多少@MyAnnotation(fileName="abc.txt")注解的方法?
  • 一个。这对问题有何影响?

标签: java testng


【解决方案1】:

你或许应该这样做

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 注释方法,您应该能够直接使用反射来查询 Method 参数以获取其注释并通过它检索文件名。

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2015-08-28
    • 2023-03-15
    • 1970-01-01
    • 2018-11-27
    相关资源
    最近更新 更多