Krishna Sarma
Krishna Sarma

Reputation: 1860

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?

Upvotes: 4

Views: 2167

Answers (4)

sina72
sina72

Reputation: 5101

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.

Upvotes: 5

AlexR
AlexR

Reputation: 115328

I know 2 solutions:

  1. Use abstract base class as it is mentioned in comment by @vikingsteve.
  2. Use Rules. You can implement your custom rule that does what you need and then add it to each test case you need.

    public class MyTest {
        @Rule Rule myBeforeAfterRule = new MyTestLifecycleRule();
    
        // your code
    }
    

The rule-based solution IMHO is more flexible because inheritance is not always applicable for all use-cases. Moreover you can combine several rules in one test case.

Upvotes: 1

vikingsteve
vikingsteve

Reputation: 40378

you can use @Before annotations in an abstract parent class like so:

public class TestMe extends TestParent {
    @Test
    public void test() {
        System.out.println("Hi, here is a test. The username is: " + getUsername());
    }
}

with parent class:

public abstract class TestParent {
    private String username;

    @Before
    public void setUp() {
        username = "fred";
    }

    public String getUsername() {
        return username;
    }
}

Upvotes: 2

André Stannek
André Stannek

Reputation: 7863

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
    }
}

Upvotes: 8

Related Questions