Thurein
Thurein

Reputation: 6895

TestNG @BeforeTest equivalent in JUnit

I found the comparison at http://www.mkyong.com/unittest/junit-4-vs-testng-comparison/. How to prepare something like @BeforeTest in JUnit?

Upvotes: 2

Views: 3570

Answers (2)

David H. Clements
David H. Clements

Reputation: 3638

Not as familiar with TestNG, but from my understanding you can do something similar it with a combination of Categories, a Suite, and @BeforeClass/@AfterClass.

For example:

import org.junit.BeforeClass;
import org.junit.experimental.categories.Categories;
import org.junit.experimental.categories.Categories.IncludeCategory;
import org.junit.runner.RunWith;
import org.junit.runners.Suite.SuiteClasses;


@RunWith(Categories.class)
@SuiteClasses(MyClassTest.class)
@IncludeCategory(IntegrationTest.class)
public class StaticTests {
    @BeforeClass
    public static void setUp() {
        System.out.println("Hello, World!");
    }
}

Then within your tests flag things as @Category(IntegrationTest.class) and you'll have a logical grouping of tests–from multiple different test classes–which you can run initialization around.

Categories let you flag specific tests for inclusion in the suite, though it is also possible (if you separate out by class in the first place) just to include the relevant ones in the suite or have them inherit from a base class that has that configuration in it. Which one is best depends on how you like to group your tests and your specific use cases.

As Matthew Farwell mentions, there's also TestRules which give you a little finer-grained control for setting up around a set of tests.

Upvotes: 1

Matthew Farwell
Matthew Farwell

Reputation: 61705

As I understand it, BeforeTest specifies a method which is run before a set of tests is run, and defineable for that set of tests. There isn't an equivalent grouping in JUnit, except for normal Suites, so you have to define a suite and use @BeforeClass and @AfterClass in your suite as normal.

If you want more complex behaviour, see TestRule, in particular ExternalResource.

Upvotes: 1

Related Questions