JUnit best practices – Use BeforeClass annotation to initialize any resource.

JUnit 4 provides BeforeClass annotation to initialize costly resources for the use of all test cases in the test class. One important thing to remember is that the method marked as BeforeClass would run only once and the resource initialized by it would be shared by all test methods. The method marked as BeforeClass would run before any other method in the test. I will share an example test that initialize a property file for all the test cases in the test class.

package com.ourownjava.unit.under.test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.junit.BeforeClass;
import org.junit.Test;
public class PropertyLoaderTest {
private static Properties properties;
public static void initPropertyFile() throws IOException{
properties = new Properties();
properties.load(new FileInputStream(new File("src/test/resources/test.properties")));
public void shouldGetValueForKey1(){
assertEquals("one", properties.get("1"));
public void shouldGetValueForKey2(){
assertEquals("two", properties.get("2"));
Property File : test.properties

JUnit BeforeClass annotation