junit一般用做测试程序
import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.junit.Before; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import junit.framework.TestCase; public class Test extends TestCase{ ClassPathXmlApplicationContext ctx; @Before public void init(){ System.out.println(1); ctx = new ClassPathXmlApplicationContext( "applicationContext.xml","mybatis-config.xml"); } @Test public void testDataSource(){ ctx = new ClassPathXmlApplicationContext( "applicationContext.xml","mybatis-config.xml"); DataSource ds = ctx.getBean( "dataSource", DataSource.class); System.out.println(ds); } @Test public void testSqlSessionFactory(){ SqlSessionFactory factory= ctx.getBean("sqlSessionFactory", SqlSessionFactory.class); System.out.println(factory); } }
运行testDataSource会输出对象信息,但运行testSqlSessionFactory会报空指针错误,这是因为junit版本的原因 目前程序使用的时3.8.1版本,此版本不支持@Before注解且Test类必须继承TestCase才能测试,如果将版本换为4.12 测试testSqlSessionFactory输出正常并且会先执行@Before注释的方法(注意此版本Test类不用继承TestCase)
1 org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@3bb4d2cb
junit配置
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>