TestNG BeforeMethod with group

2022-09-04 03:38:33

我想知道 组的用法。在 http://testng.org/javadoc/org/testng/annotations/BeforeMethod.html 它说:@BeforeMethod

alwaysRun:如果设置为 true,则无论此配置方法属于哪个组,都将运行它。

所以我有以下类:

public class BeforeTest {
private static final Logger LOG = Logger.getLogger(BeforeTest.class);
@BeforeMethod(groups = {"g1"}, alwaysRun = false)
public void setUpG1(){
    sleep();
    LOG.info("BeforeMethod G1");
}

@Test(groups = {"g1"})
public void g1Test(){
    sleep();
    LOG.info("g1Test()");
}

@BeforeMethod(groups = {"g2"}, alwaysRun = false)
public void setUpG2(){
    sleep();
    LOG.info("BeforeMethod G2");
}

@Test(groups = {"g2"})
public void g2Test(){
    sleep();
    LOG.info("g2Test()");
}


private void sleep(){
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
}

哪些输出:

BeforeMethod G1
BeforeMethod G2
g1Test()
BeforeMethod G1
BeforeMethod G2
g2Test()

除了我认为 awaysRun 在默认情况下是错误的这一事实之外,任何人都可以向我解释为什么在每次测试之前都调用这两种方法,而不考虑组?像@Test(skipBeforeMethod = “setUpG1”)这样的东西也可以工作。

我正在使用IntelliJ IDEA CE 10.5.2。我也用gradle 1.0-milestone-3运行它。


答案 1

这是因为该标志仅指示方法是否属于组。启用该组后,它将始终执行,即在所有测试方法之前执行,而不管测试方法属于哪个组。默认情况下,所有组都处于启用状态。groups

如果希望仅对某些组的测试执行该方法,则需要指定 。onlyForGroups

public class BeforeTest {

    private static final Logger LOG = Logger.getLogger(BeforeTest.class);

    @BeforeMethod(onlyForGroups = { "g1" })
    public void setUpG1() {
        sleep();
        LOG.info("BeforeMethod G1");
    }

    @Test(groups = { "g1" })
    public void g1Test() {
        sleep();
        LOG.info("g1Test()");
    }

    @BeforeMethod(onlyForGroups = { "g2" }, alwaysRun = false)
    public void setUpG2() {
        sleep();
        LOG.info("BeforeMethod G2");
    }

    @Test(groups = { "g2" })
    public void g2Test() {
        sleep();
        LOG.info("g2Test()");
    }

    private void sleep() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

输出为

BeforeMethod G1
g1Test()
BeforeMethod G2
g2Test()

答案 2

您如何调用TestNG?是否正在运行任何组?

如果未运行任何操作,则两个@BeforeMethods都将运行。如果你运行“g1”,只有setupG1会运行,等等...


推荐