Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does TestNG support something like JUnit4's @Rule?

Tags:

junit4

testng

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.

like image 603
Francisco Avatar asked May 23 '11 15:05

Francisco


People also ask

How TestNG is different from JUnit?

Differences between JUnit and TestNG : JUnit is an open-source framework used to trigger and write tests. TestNG is a Java-based framework that is an upgraded option for running tests. JUnit does not support to run parallel tests. TestNG can run parallel tests.

Which is better TestNG or JUnit?

Both TestNG and JUnit are Testing frameworks used for Unit Testing. TestNG is inspired by JUnit, so in a way these are similar. Few more functionalities are added to TestNG which makes it more powerful than JUnit. Both JUnit and TestNG are without a doubt the most popular testing frameworks out there.

Why we use TestNG instead of JUnit?

We can use TestNG run() method to execute tests from the java main method. Both of them supports execution of test cases from java main method. JUnit provides enough assertion methods to compare expected and actual test results. TestNG provides enough assertion methods to compare expected and actual test results.


1 Answers

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.

like image 194
Cedric Beust Avatar answered Sep 28 '22 07:09

Cedric Beust