如何添加分组和依赖于@BeforeMethod在TestNG的(How to add Groupin

2019-10-19 15:26发布

有没有什么办法让依赖于@BeforeMethod上@测试,因为在我的情况不同TestMethod的有不同的设置,我需要一个设置取决于TestMethod的。 我在这里添加一些代码片断以便更好地理解

@BeforeMethod(groups = {"gp2"})
public void setUp1() {
    System.out.println("SetUp 1 is done");
}

@BeforeMethod(groups = {"gp1"}, dependsOnGroups = {"tgp1"})
public void setUp2() {
    System.out.println("SetUp 2 is done");
}

@Test(timeOut = 1, groups = {"tgp1"})
public void testMethod() throws InterruptedException {
    Thread.sleep(2000);
    System.out.println("TestMethod() From Group1");
}

@Test(dependsOnMethods = {"testMethod"}, groups = {"tgp2"})
public void anotherTestMethod() {
    System.out.println("AnotherTestMethod()From Group1 and Group2");
}

产量

SETUP 1完成设置2完成

但我需要设置1()应执行不SETUP2(),因为它是依赖于tgp1组

另一件事我观察到,如果我改变,从依赖

@BeforeMethod(groups = {"gp1"}, dependsOnGroups = {"tgp1"})

@BeforeMethod(groups = {"gp1"}, dependsOnMethods = {"testMethod"}) 

然后我像一个异常

 setUp2() is depending on method public void testMethod() throws java.lang.InterruptedException, which is not annotated with @Test or not included.

我需要执行应该在这个步骤

设置1 ----> testMethod1()------->设置2 ---------> testMethod2()

我需要这个,因为不同TestMethods有不同的工作,它有不同的设置()。

Answer 1:

你的情况,你可以简单地调用来自相应的测试方法,相应的设置方法,你真的没有共同@BeforeMethod为每个测试。

或者,你可以在这两个测试分成各自具有不同的测试类@BeforeMethod

或者你也可以做基于测试方法的名称与一个条件建立呼叫@BeforeMethod如下方法。 这里@BeforeMethod可以声明类型的参数java.lang.reflect.Method 。 该参数将收到的测试方法将被调用一次这个@BeforeMethod完成

@BeforeMethod
public void setUp(Method method) {
    if (method.getName().equals("testMethod")) {
        setUp1();
    } else if (method.getName().equals("anotherTestMethod")) {
        setUp2();
    }
}

public void setUp2() {
    System.out.println("SetUp 2 is done");
}

public void setUp1() {
    System.out.println("SetUp 1 is done");
}    


Answer 2:

该目的@BeforeMethod是带有加注解的各测试方法之前运行@Test并做一些创建工作。 因此,这是有点混乱,你为什么会想产生依赖性,工程其他方式 - 执行的测试方法建立前法。 通常的做法是以下几点:

@BeforeMethod
public void setUp() {
}

@Test
public void testMethod1() {
}

@Test
public void testMethod2() {
}

其中最有可能产生以下执行列表:

设定()
testMethod1()
设定()
testMethod2()

如果有多个@BeforeMethods所有的人都会在之前运行@Test方法。

现在,如果你想运行不同的群体,你会与注释不同群体的不同的方法和规定,要运行的组。 但是,对于您需要提供任何的testng.xml或指定执行哪个组。


编辑(基于额外的评论):

我建议以下方法之一:

  1. 单独的测试方法为不同类别,并已@BeforeMethod在每个类执行所需的设置。 这尤其是有道理的,如果该测试覆盖不同的领域。
  2. 定义不同的基团,并把相应的测试和设置方法为相同的基团。 此选项可以让你混合和匹配测试方法建立的方法。

有些东西,是从你的问题不清楚,但如果有关可能从建议的方法中获益:

  • 是否有需要依赖?
  • 请问订单或测试重要吗?


文章来源: How to add Grouping and Dependency in @BeforeMethod On TestNG