Reputation: 599
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
Reputation: 95614
For each test method:
@Before
method is run@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