ML.
ML.

Reputation: 599

How do you use the @Before annotation for multiple test cases?

For Junit testing, how exactly does the @Before annotation work? I want to be able to pass in a parameter to mark which test case I'm running in my class because each test case has a different URL I am passing in.

Upvotes: 0

Views: 75

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95614

For each test method:

  1. Each @Before method is run
  2. Then the test method is run
  3. And then each @After method is run.

In your situation I would simply favor extracting to a private method:

@RunWith(JUnit4.class)
public class YourClass {

  private void prepareTest(String url) { /* ... */ }

  @Test public void firstTest() {
    prepareTest("http://foo.bar/");
    /* ... */
  }

  @Test public void secondTest() {
    prepareTest("http://baz.quux/");
    /* ... */
  }
}

If the number of test cases truly warrants separate parameterized treatment, you may consider using the Parameterized test runner, which allows you to specify a List<Object[]> used for constructor arguments on the test class itself.

(You may also consider creating a custom JUnit4 Runner, but each test method would need some way or another to specify the URL it takes, so that may not wind up any safer or more elegant than the solution above.)

Upvotes: 3

Related Questions