本文介绍了如何在@BeforeMethod On TestNG 中添加分组和依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在@Test 上依赖@BeforeMethod,因为在我的场景中,不同的TestMethod 有不同的设置,我需要一个依赖于TestMethod 的设置.我在这里添加了一些代码片段以便更好地理解

Is there any way to give dependency to @BeforeMethod on @Test,because in my scenario different TestMethod have different setup and I need one setup depends on TestMethod. I add here some code snippet for better understanding

@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");
}

输出

设置 1 已完成设置 2 完成

SetUp 1 is doneSetUp 2 is done

但我需要执行 setUp1() 而不是 setUp2() 因为它取决于 tgp1 组.

我观察到的另一件事是,如果我从

Another thing I observe that,If I change dependencies from

@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.

我需要执行的应该是这一步

I need execution should be on this steps

SetUp1---->testMethod1()------->SetUp2--------->testMethod2()

SetUp1---->testMethod1()------->SetUp2--------->testMethod2()

我需要这个,因为不同的 TestMethods 有不同的工作,它有不同的 SetUp().

I need this because different TestMethods have different work and it have different SetUp().

推荐答案

在你的情况下,你可以简单地从各自的 Test 方法调用各自的 setUp 方法,因为你真的没有共同的 @BeforeMethod for每次测试.

In your case, you can simply call respective setUp method from respective Test method as you really don't have common @BeforeMethod for each Test.

或者您可以将这两个测试分成不同的测试类,每个类都有一个 @BeforeMethod.

Or you can separate these two tests into different Test classes each having a @BeforeMethod.

或者,您可以使用一种 @BeforeMethod 方法根据测试方法名称进行条件设置调用,如下所示.这里@BeforeMethod 可以声明一个java.lang.reflect.Method 类型的参数.此参数将接收此@BeforeMethod 完成后将调用的测试方法

Or you can do conditional setup call based on test method name with one @BeforeMethod method as below. Here @BeforeMethod can declare a parameter of type java.lang.reflect.Method. This parameter will receive the test method that will be called once this @BeforeMethod finishes

@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");
}    

这篇关于如何在@BeforeMethod On TestNG 中添加分组和依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 05:23