Mock tests, Interview questions, Tutorials and Tech news
 
 
Home > Programming / tutorials > @BeforeClass and @AfterClass in Junit

@BeforeClass and @AfterClass in Junit

December 14th, 2010 Vinay Leave a comment Go to comments

This is one of the best features which have been part of JUnit4, the @BeforeClass and @AfterClass annotated methods .

@BeforeClass and @AfterClass annotated will be run exactly once during the test run .

@BeforeClass is run at the very beginning and @AfterClass is run at the end of the test as a whole. In fact, they’re run before the test class is even constructed, which is why they must be declared static.

An example

@RunWith(BlockJUnit4ClassRunner.class)
public class MySpringIntegrationTest extends AbstractDependencyInjectionSpringContextTests {

private static int ID = 1111;

@Autowired
private MyBean myBean;

protected String[] getConfigLocations()
{
return new String[]{“classpath:applicationContext-*.xml”};
}

@BeforeClass
public static void before() {

// all the set up code will come here. for eg connecting to database
}

}

What is difference between @Before and @BeforeClass ?

The @Before and @After methods will be run before and after every test case and will be run multiple times during a test run.

If you don’t want to set up static initializers for one time initialization and are not particular about using JUnit, use TestNG. TestNG supports non static one time initialization with a variety of configuration options, all using annotations. In TestNG, this would be equivalent to:

[[code]]czoxMDE6XCJAb3JnLnRlc3RuZy5hbm5vdGF0aW9ucy5CZWZvcmVDbGFzcw0KcHVibGljIHZvaWQgc2V0VXBPbmNlKCkgew0KwqAgwqB7WyYqJl19Ly8gT25lIHRpbWUgaW5pdGlhbGl6YXRpb24uDQp9DQpcIjt7WyYqJl19[[/code]]

For teardown,
[[code]]czo5ODpcIkBvcmcudGVzdG5nLmFubm90YXRpb25zLkFmdGVyQ2xhc3MNCnB1YmxpYyB2b2lkIHRlYXJEb3duT25jZSgpIHsNCsKgIMJ7WyYqJl19oC8vIE9uZSB0aW1lIHRlYXIgZG93bi4NCn0NClwiO3tbJiomXX0=[[/code]]

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • IndianPad
  • Reddit
Categories: Programming / tutorials Tags:
Get Adobe Flash playerPlugin by wpburn.com wordpress themes