首页 > 解决方案 > Testng - 如何在为所有数据提供者运行测试方法后运行清理代码?

问题描述

我有一个 testng 测试(如下),我对数据提供者“junkDP”给出的每个数组使用一个“totalAmount”值。我想重置“totalAmount”,只有在“junkDP”中的每个数组运行“test”方法之后。这在 testng 中可能吗?怎么做 ?

请注意 @AfterMethod 和 @AfterTest 不会做我想做的事。@AfterMethod 在“junkDP”中的第一个数组之后为每个数组运行“test”方法之前重置“totalAmount”。@AfterTest 在@AfterClass 之后运行。

编码:

import org.testng.annotations.DataProvider;
import org.testng.annotations.*;

public class JUNKdP {

    @DataProvider( name = "junkDP")
    public static Object[][] junkDP() {
        Object [] [] dataSet = new Object[][] {
                new Object[] {1, 2},
                new Object[] {3, 4},
                new Object[] {5, 6}};
        return dataSet;
    }

}


public class JUNK {

    private int totalAmount = 0;

    @BeforeClass
    public void beforeClass(){System.out.println("BeforeClass\n");}

    @BeforeMethod
    public void beforeMethod(){
        System.out.println("BeforeMethod\n");
    }

    @AfterMethod
    public void afterMethod(){
        System.out.println("AfterMethod\n");
    }

    @AfterTest
    public void afterTest(){
        System.out.println("AfterTest\n");
        this.totalAmount = 0;
        System.out.println("Reset total amount to 0");
    }

    @AfterClass
    public void afterClass(){System.out.println("AfterClass\n");}

    @Test(dataProvider = "junkDP", dataProviderClass = JUNKdP.class, enabled = true)
    public void test(int a, int b){
        System.out.println("Test method");
        int sum = a + b;
        System.out.println("Sum: " + sum);
        this.totalAmount = this.totalAmount + sum;
        System.out.println("totalAmount: " + this.totalAmount + "\n");
    }
}

输出:

BeforeClass

BeforeMethod

Test method
Sum: 3
totalAmount: 3

AfterMethod

BeforeMethod

Test method
Sum: 7
totalAmount: 10

AfterMethod

BeforeMethod

Test method
Sum: 11
totalAmount: 21

AfterMethod

AfterClass

AfterTest

Reset total amount to 0

标签: javatestng

解决方案


如果我理解这个问题,您是在测试方法之后寻找执行者吗?

...如果是,取决于测试运行者

给你,testng是怎么做的:

http://testng.org/doc/documentation-main.html#annotations

@AfterTest 或 @AfterMethod


推荐阅读