【问题标题】:Running a @BeforeMethod testNG annotation when the method *contains* a group当方法*包含*一个组时运行@BeforeMethod testNG注解
【发布时间】:2016-11-15 17:52:12
【问题描述】:

如果我有一个带有一个组的 beforeMethod,并且我运行了一个不同的组,但在该组中存在一个测试,其中包含我正在运行的组以及具有 beforeMethod 的组,我想要那个测试运行它的 before 方法。比如:

@BeforeMethod(groups = "a")
public void setupForGroupA() {
...
}

@Test(groups = {"supplemental", "a"})
public void test() {
...
}

当我使用 groups=supplemental 运行 testNG 时,我仍然希望 beforeMethod 在测试之前运行,但因为 group 是补充而不是 'a',所以它不会。

这对我来说似乎是一个如此明显的功能,我觉得我一定是错误地使用了组,所以我也想解释一下我的工作流程,以防我的问题出在哪里。

我正在使用组来定义不同的测试层,以及他们是否需要创建自己的帐户,或者他们是否需要使用代理来访问他们的数据等。我会有一组烟雾,补充和回归以及 uniqueAccount、proxy 等组。我不需要为第一个分组进行特定设置,但这些是我传入以在 maven 中运行的组。我需要对后一组进行特定设置,但我不想只运行需要代理或需要唯一帐户的测试。

【问题讨论】:

    标签: java testng integration-testing


    【解决方案1】:

    在运行时不会评估组配置。 test 方法不会激活 setupForGroupA 方法。

    该功能用于查找要运行的方法。 根据下面的例子:

    @BeforeMethod(groups = "a")
    public void setupForGroupA() {
    ...
    }
    
    @Test(groups = {"supplemental", "a"})
    public void test() {
    ...
    }
    
    @Test(groups = {"supplemental"})
    public void test2() {
    ...
    }
    

    如果您使用组“a”运行此类,它将运行 setupForGroupAtest 方法,因为它们标有组“a”。

    如果您使用“补充”组运行此类,它将运行 testtest2 方法,因为它们标有“补充”组。

    看起来您对某些方法有不同的行为,因此一个好的方法是将不同类中的方法分开并按类选择测试,而不是按组选择测试。

    public class A {
      @BeforeMethod
      public void setupForGroupA() {
        ...
      }
    
      @Test
      public void test() {
        ...
      }
    }
    

    public class Supplemental {
      @Test
      public void test2() {
        ...
      }
    }
    

    运行类 A 将只运行 setupForGroupAtest。 运行类补充将只运行test2。 运行这两个类将运行一切。

    如果您想同时运行这两个类并通过其他方式进行过滤,您可以使用a method interceptor 实现您自己的逻辑:

    @MyCustomAnnotation(tags = "a", "supplemental")
    public class A {
      ...
    }
    
    @MyCustomAnnotation(tags = "supplemental")
    public class Supplemental {
      ...
    }
    
    public class MyInterceptor implements IMethodInterceptor {
    
      public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
        // for each method, if its class contains the expected tag, then add it to the list
        // expect tag can be passed by a system property or in a parameter from the suite file (available from ITestContext)
      }
    }
    

    【讨论】:

      【解决方案2】:

      如果我猜对了,你想每次都运行你的 before 方法。在这种情况下,您可以像这样为之前的方法设置 alwaysRun=true-

      @BeforeMethod(alwaysRun = true, groups = "a")
      public void setupForGroupA() {
      ...
      }
      

      这是您想要的解决方案之一。

      【讨论】:

      • 所以为了扩展这个例子,我可以添加另一个方法'test2',组补充,但没有组'a'。在这种情况下,我希望 before 方法在“test”之前运行,而不是在“test2”之前运行。
      猜你喜欢
      • 1970-01-01
      • 2015-07-18
      • 2012-11-11
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      相关资源
      最近更新 更多