What is the difference between @Before, @BeforeClass, @After and @AfterClass annotations?
@Beforepublic void method()
TheBeforeannotation indicates that this method must be executed before each test in the class, so as to execute some preconditions necessary for the test.@BeforeClasspublic static void method()
TheBeforeClassannotation 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).
@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 :
Post a Comment