Search code examples
junittest-suite

TestSuite JUnit -> Each TestCase has same @Before etc


I'm just writing som Selenium WebDriver tests with JUnit 4.

Test Cases are grouped by JUnit TestSuite. Each test case (test class) has the same @Rule @BeforeTest @AfterTest

How can i realize this in JUnit TestSuite, so that I don't have the same code for @Rule, @BeforeTest and @AfterTest in each test case (class)?

//edit: maybe i define an abstract testcase class, which i extend from each test case?


Solution

  • You could merge the code of @Rule, @BeforeTest and @AfterTest into a single rule.

    public class TheMergedRule implements TestRule {
      private final TestRule theCurrentRule = ...
    
      public Statement apply(final Statement base, final Description description) {
        return new Statement() {
          theCodeOfBefore();
          theCurrentRule.apply(base, description);
          theCodeOfAfter();
        }
      }
    
      public void theCodeOfBefore() {
        ...
      }
    
      public void theCodeOfAfter() {
        ...
      }
    }