天天看点

Spring学习——Spring整合Junit4使用方法这虽然看起来并不简单多少,但是如果有很多测试方法都要用到该对象时,会减轻很大的代码量。

对于以前常使用junit的程序员来说,肯定知道Junit4的好处。

当我们学习Spring时,如果我们想在测试方法中获取Spring管理的对象,按照一般步骤,需要创建读取Spring配置的对象,然后通过该对象获得实体。

例:获取Hibernate中的SessionFactory对象。如果我们有多个测试Hibernate的方法,按照普通方法:

ClassPathXmlApplicationContext cpxa = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
SessionFactory sessionFactory = (SessionFactory )cpxa.getBean("sessionFactory");
           

要在每个方法中都要写上上面这段代码才能获取到SessionFactory工厂,想想都烦恼。

Spring想到了这一点,帮我们优化了使用方法,我们只要学会使用就可以:

  • 1. 在测试类上使用注解:

  • // 每次执行此类中的测试方法时,都会为我们自动创建Spring容器
    @RunWith(SpringJUnit4ClassRunner.class)
    // 指定Spring配置文件的路径
    @ContextConfiguration("classpath:applicationContext.xml")
    public class Test {
    
    }
               
  •  2. 创建对象引用属性,使用注解注入属性:

  • @Resource(name="sessionFactory")
    	private SessionFactory sf;
               
  • 这样,我们在测试方法中用到该对象时,直接使用就可以,无需再手动获取,如:

  • @Test
    	public void testfun() {
    		// 使用Spring创建的SessionFactory对象创建session
    		Session session = sf.openSession();
    		Transaction tst = session.beginTransaction();
    		// 创建对象
    		TestMain tm = new TestMain();
    		tm.setName("test3");
    		// 持久化对象
    		session.save(tm);
    		// 事务提交、关闭资源
    		tst.commit();
    		session.close();
    	}
               

这虽然看起来并不简单多少,但是如果有很多测试方法都要用到该对象时,会减轻很大的代码量。