1 package guru.mikelue.jdut.junit4.test; 2 3 import javax.sql.DataSource; 4 5 import org.junit.ClassRule; 6 import org.junit.rules.ExternalResource; 7 import org.slf4j.Logger; 8 import org.slf4j.LoggerFactory; 9 import org.springframework.context.ApplicationContext; 10 import org.springframework.context.annotation.AnnotationConfigApplicationContext; 11 12 public abstract class AbstractDataSourceTestBase { 13 private Logger logger = LoggerFactory.getLogger(AbstractDataSourceTestBase.class); 14 15 protected AbstractDataSourceTestBase() {} 16 17 private static AnnotationConfigApplicationContext ctx; 18 19 @ClassRule 20 public final static ExternalResource dataSourceResource = new ExternalResource() { 21 @Override 22 protected void before() 23 { 24 getApplicationContext(); 25 } 26 27 @Override 28 protected void after() 29 { 30 ctx.close(); 31 ctx = null; 32 } 33 }; 34 35 protected Logger getLogger() 36 { 37 return logger; 38 } 39 40 protected static ApplicationContext getApplicationContext() 41 { 42 if (ctx == null) { 43 ctx = new AnnotationConfigApplicationContext(); 44 ctx.register(DataSourceContext.class); 45 ctx.refresh(); 46 } 47 48 return ctx; 49 } 50 51 protected static DataSource getDataSource() 52 { 53 return getApplicationContext().getBean(DataSource.class); 54 } 55 }