【问题标题】:Execution order of methods when @Test is at class level@Test 在类级别时方法的执行顺序
【发布时间】:2021-07-19 23:33:18
【问题描述】:

关于TestNG测试的执行顺序有很多问题,但我还没有找到专门回答这个问题的问题——除非我找不到。

我知道有些事情可以实现我正在寻找的东西,例如:

  1. @Test 在类中的每个测试方法上方使用Priority
  2. @Test 在类中的每个测试方法上方使用Depends on
  3. 在 XML 文件中使用preserve-order

不过,我想知道的是:

如果在类级别而不是方法级别声明@Test,如何“保留”声明方法的顺序?你能做到吗?

例如,如果我的班级是这样的:

@Test
public class mySampleClass
{
    public void test()
    {
        //Run first - First method in the class
    }
    
    public void run()
    {
        //Run second - Second method in the class
    }
    
    public void execute()
    {
        //Run last - Last method in the class
    }
}

我能否确保当我运行此方法时,方法按它们在类中的顺序而不是按字母顺序执行?

【问题讨论】:

  • 为什么单元测试需要顺序?如果是单元测试。
  • 感谢@VeKe 的回复 :)。它实际上不是单元测试。

标签: java testng


【解决方案1】:

不知道为什么你希望你的测试以这种方式运行,即使不能直接执行,也可以使用MethodInterceptor:

public class MyInterceptor implements IMethodInterceptor {

    // keep your list of method names in order
    private static final List<String> order = List.of("test", "run", "execute");
    
    @Override
    public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
        methods.sort(Comparator.comparing(m -> order.indexOf(m.getMethod().getMethodName())));
        return methods;
    }
}

现在将@Listeners(value = MyInterceptor.class) 注释添加到您的类中。

注意: List.of 仅在 java 9+ 中可用,如果您使用的是较低版本,则可以使用 Arrays.asList。

【讨论】:

  • 感谢您的回答:) 我不需要像我在上面的问题中提出的那样专门运行它,但是我想知道是否可以这样做。更容易描述性地命名方法并将它们按照您想要执行的顺序放置,而不是每个方法(如果没有明确需要)而不是 @Test,您只需在类级别 @Test 就完成了。
  • @EitelDagnin 无论如何,方法拦截器可用于以我们喜欢的任何方式修改订单/添加/删除测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
相关资源
最近更新 更多