Does TestNG support something like JUnit4's @Rule?

坚强是说给别人听的谎言 提交于 2019-11-27 14:21:22

问题


Does TestNG have something like @Rule? I am thinking specifically about:

@Rule public TemporaryFolder folder = ...

Or even

@Rule public MethodRule globalTimeout = new Timeout(20);

I am aware that I can manually implement these things using setUp() and tearDown() equivalents, but these don't give me the convenience that I get using @Rule.


回答1:


Rules are pretty easy to emulate, for example with super classes:

public void Base {
  @BeforeMethod
  public void createTempDir() { ... }

  @AfterMethod
  public void deleteTempDir() { ... }
}

public void MyTest extends Base {
  @Test
  ...
}

If you extend Base, a temporary directory will always be automatically created and then deleted.

The advantage of this approach over Rules is that Rules are always class scoped, while with TestNG, you can implement them around methods, tests, classes, groups and even suites.




回答2:


BeforeClass/AfterClass of TestNG can simulate something like the rule/ruleClass of JUnit, but there are some functions and effects that these classes cannot replicate, such as: repeat, filter, etc.

However, there are some interfaces provided by TestNG that could be used to simulate these functions instead, e.g. IAnnotationTransformer, IMethodInterceptor.



来源:https://stackoverflow.com/questions/6099633/does-testng-support-something-like-junit4s-rule

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!