如何使用@BeforeTest注释在testng中获取方法名称

时间:2018-06-06 06:34:27

标签: java rest testng jxl

我正在使用Rest Assured进行休息API测试,并且我使用@BeforeTest注释来调用jxl数据并在@Dataprovider注释的帮助下将结果写入其中以传递测试数据。

但是在这里我总共有4个api,我想根据不同类的@Test注释中的方法名称来阅读特定休息API的特定表格。

示例:

1.cardvalidation - 验证表 2.购买 - 购买表 3.取消 - 取消购买单

例如,如果方法名称是cardvalidation,那么我只会选择所有4个API的验证表等,并使用Before Method annotation,但它只为一个写入结果行不是所有测试数据行。

示例代码:

@BeforeMethod
    public void excelWriter(Method method) throws BiffException, IOException, RowsExceededException, WriteException {

        File file = new File(inputFile);
        FileInputStream testFile = new FileInputStream(file);
        Workbook workBook = Workbook.getWorkbook(testFile);

        String methodName = method.getName();

        if(methodName.equals("validateTesting")) {
            sheet = workBook.getSheet("Validate_TestData");
        }else if(methodName.equals("purchaseTesting")) {
            sheet = workBook.getSheet("Purchase_TestData");
        }

        int rows = sheet.getRows();
        int columns = sheet.getColumns();

        String dataFile[][] = new String[rows][columns];

        File outputResults = new File(outputFile);
        // Write data into file
        FileOutputStream fileOutputStream = new FileOutputStream(outputResults);
        // Create the workbook
        workbookCopy = Workbook.createWorkbook(fileOutputStream);

        if(methodName.equals("validateTesting")) {
            writablesh = workbookCopy.createSheet("Validate_Results", 0);
        }else if(methodName.equals("purchaseTesting")) {
            writablesh = workbookCopy.createSheet("Purchase_Results", 1);
        }


        // Copy all data from source file to Destination File

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                dataFile[i][j] = sheet.getCell(j, i).getContents();
                Label l = new Label(j, i, dataFile[i][j]);

                Label L2 = new Label(13, 0, "Results");
                writablesh.addCell(l);
                writablesh.addCell(L2);

            }
        }

    }

1 个答案:

答案 0 :(得分:0)

尝试实现接口IInvokedMethodListener,然后您必须实现以下方法:

/**
 * A listener that gets invoked before and after a method is invoked by TestNG.
 * This listener will only be invoked for configuration and test methods.
 */

void beforeInvocation(IInvokedMethod method, ITestResult testResult);
void afterInvocation(IInvokedMethod method, ITestResult testResult);

所以这符合您的需求。

以下是实现此目的的示例代码:

@Override
public synchronized void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
    Class<?> clazz = (Class<?>) method.getTestMethod().getRealClass();
    Method method = method.getTestMethod().getMethod());

     // so each method You call is basically invoked, and it has to be processed.

}

试试这个。希望它有所帮助。