Is there a equivalent of testNG's @BeforeSuite in JUnit 4? Is there a equivalent of testNG's @BeforeSuite in JUnit 4? selenium selenium

Is there a equivalent of testNG's @BeforeSuite in JUnit 4?


You can adapt the solution for setting a global variable for a suite in this answer to JUnit 4 Test invocation.

Basically, you extend Suite to create MySuite. This creates a static variable/method which is accessible from your tests. Then, in your tests, you check the value of this variable. If it's set, you use the value. If not, then you get it. This allows you to run a single test and a suite of tests, but you'll only ask the user once.

So, your suite will look like:

public class MySuite extends Suite {    public static String url;    /**     * Called reflectively on classes annotated with <code>@RunWith(Suite.class)</code>     *      * @param klass the root class     * @param builder builds runners for classes in the suite     * @throws InitializationError     */    public MySuite(Class<?> klass, RunnerBuilder builder) throws InitializationError {        this(builder, klass, getAnnotatedClasses(klass));        // put your global setup here        MySuite.url = getUrlFromUser();    }}

This would be used in your Suite like so:

@RunWith(MySuite.class)@SuiteClasses({FooTest.class, BarTest.class, BazTest.class});

Then, in your test classes, you can either do something in the @Before/@After, or better look at TestRule, or if you want Before and After behaviour, look at ExternalResource. ExternalResource looks like this:

public static class FooTest {    private String url;    @Rule    public ExternalResource resource= new ExternalResource() {        @Override        protected void before() throws Throwable {            url = (MySuite.url != null) ? MySuite.url : getUrlFromUser();        };        @Override        protected void after() {            // if necessary        };    };    @Test    public void testFoo() {        // something which uses resource.url    }}

You can of course externalize the ExternalResource class, and use it from multiple Test Cases.


I think the main functionality of TestNG that will be useful here is not just @BeforeSuite but @DataProviders, which make it trivial to run the same test with a different set of values (and won't require you to use statics, which always become a liability down the road).

You might also be interested in TestNG's scripting support, which makes it trivial to ask the user for some input before the tests start, here is an example of what you can do with BeanShell.


It might make sense to group tests so that the test suite will have the same @Before method code, so you have a test suite for each separate.

Another option might be to use the same base url for each test but navigate to the specific page by getting selenium to click through to where you want to carry out the test.