发生异常时如何停止TestNG执行器

发生异常时如何停止TestNG执行器

本文介绍了发生异常时如何停止TestNG执行器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以编程方式运行 TestNG.我有一个用例,当任何测试发生任何异常时,我需要停止执行者.我的问题是:

I am running TestNG programmatically. I have a use case where I need to stop the executioner when any exception occurred by any tests. My questions are:

  1. 当测试或配置方法发生异常时,强制 TestNG 停止执行的最佳方法是什么?
  2. 以编程方式执行时在控制台中捕获异常?

这是执行测试运行器的代码片段:

Here is the code snippet for executing test runner:

TestListenerAdapter tla = new TestListenerAdapter();
IMethodInterceptor im = new  TestMethodInterceptor();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { TestClass1.class, TestClass2.class});
testng.addListener(tla);
testng.setMethodInterceptor(im);
testng.run();

推荐答案

使用 IHookable,如上一个答案中所述,是通过跳过以下所有内容来模拟完整测试套件取消的好方法方法.然而,它不会被通知(因此不会取消)配置方法(例如用 @BeforeClass@BeforeMethod 注释的方法),通常这是真正处理的地方正在进行中.

Using an IHookable, as described in the previous answer, is a good way to simulate a complete test suite cancellation by skipping all following methods. However, it is not notified for (and therefore does not cancel) configuration methods (e.g. methods annotated with @BeforeClass and @BeforeMethod), and often this is where the real processing is going on.

要解决这个问题,您可以将 IHookable 替换为 IInvokedMethodListener,其 beforeInvocation 方法也会为配置方法触发.如果你想取消其余的测试执行,每次都抛出一个 SkipException beforeInvocation 被调用.

To deal with this, you can replace the IHookable by an IInvokedMethodListener, whose beforeInvocation method wil also fire for configuration methods. If you want to cancel the rest of your test executions, throw a SkipException everytime beforeInvocation is called.

就我而言,这成功取消了所有进一步处理,而无需对测试结构做出任何假设.

In my case, this successfully cancelled all further processing without making any assumptions about the test structure.

这篇关于发生异常时如何停止TestNG执行器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:52