Wednesday, January 28, 2015

More Tips towards JUnit Framework

What is the difference between @Before, @BeforeClass, @After and @AfterClass annotations?

  • @Before public void method()
    The Before annotation indicates that this method must be executed before each test in the class, so as to execute some preconditions necessary for the test.
  • @BeforeClass public static void method()
    The BeforeClass annotation indicates that the static method to which is attached must be executed once and before all tests in the class. That happens when the test methods share computationally expensive setup (e.g. connect to database).
Note : @Before and @BeforeClass will be called after the superclass @Before or @BeforeClass execution if your class is inherited.

@After and @AfterClass also follow the same pattern where method / class call after the execution of @Test method or class completion. @AfterClass (eg close to database). Again superclass method will execute first if your class inherited. @AfterClass method also should be static.

Here is a simple example:


 public class Example {    DatabaseConnection database;
    @BeforeClass public static void login() {
        database= ...;
    }    @Before public void beforeEachTestAnnotateMethod() { }      

@Test public void something() {
          ...
    }
    @Test public void somethingElse() {
          ...
    }    @After public void afterEachTestAnnotateMethod() { }     

@AfterClass public static void logout() {
          database.logout();
    }
 }


No comments :

// Below script tag for SyntaxHighLighter