package net.northking.cctp.element.test.junit;

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.northking.cctp.element.test.AbstractLibraryTest;

/**
 * JUnit4ClassRunner<br>
 * Example:
 * 
 * <pre>
 * &#64;RunWith(LibraryJUnit4ClassRunner.class)
 * </pre>
 * 
 * @author fengxiang.zhang
 * @since 1.0
 */
public class LibraryJUnit4ClassRunner extends BlockJUnit4ClassRunner {

	private static final Logger logger = LoggerFactory.getLogger(LibraryJUnit4ClassRunner.class);
	private Object testInstance;

	public LibraryJUnit4ClassRunner(Class<?> testClass) throws InitializationError {
		super(testClass);
		checkParentClass(testClass);
	}

	private static void checkParentClass(Class<?> testClass) throws InitializationError {
		if (!AbstractLibraryTest.class.isAssignableFrom(testClass)) {
			logger.error(
					String.format("The testClass %s Should be inherit AbstractLibraryTest.class",
							testClass.getCanonicalName()));
			throw new InitializationError(
					String.format("The testClass %s Should be inherit AbstractLibraryTest.class",
							testClass.getCanonicalName()));
		}
	}

	@Override
	protected Object createTest() throws Exception {
		if (testInstance == null) {
			logger.debug("create test instance.");
			testInstance = super.createTest();
		}
		return testInstance;
	}
}