Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 443
Krishna Sarma Avatar asked Dec 04 '22 06:12

Krishna Sarma


1 Answers

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
    }
}
like image 60
André Stannek Avatar answered Jan 05 '23 13:01

André Stannek