Q:

Common @before and @after for test classes in junit

Is it possible to have a common @Before and @After fixtures that can be used across multiple test classes?
I have segregated the tests (into classes) based on modules (Inventory, Sales, Purchase etc.). For all these tests, user Login is a prerequisite, currently I am having it in @Before for each class. The problem is when I need to change user id or password, I need to change in every class. Is there a way to write the @Before / @After that can be used in all the test classes? Does testsuite come handy by any means in this case?

A:

The @Before and @After are applicable to inheritance:
public abstract class AbstractTestCase {

    @Before
    public void setUp() {
        // do common stuff
    }
}

If you want to do specific stuff in each test case you can override it:
public class ConcreteTestCase extends AbstractTestCase {

    @Before
    @Override
    public void setUp() {
        super.setUp();
        // do specific stuff
    }
}

A:

You can create a @ClassRule for your test suite. It is invoked for each test. See API and Example for ExternalResource on how to apply before/after.

