spring dbunit junit hibernate 注解方式测试集合

一、测试基类上添加RunWith等注解,准备测试前的参数设定工作,

RunWith(SpringJUnit4ClassRunner.class):spring 来管理测试

ContextConfiguration("/beans.xml") 指定spring初始化bean文件

TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class  })  测试时以注入方式注入相关参数

@Inject
 private SessionFactory sessionFactory;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/beans.xml")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class  })
public class testUserModel  {
......
}

二、解决session延迟加载的问题:

测试时经常会出现no session的情况,这时就要在测试基类中初始化session.

为测试基类增加属性

private SessionFactory sessionFactory;
 @Inject
 private SessionFactory sessionFactory;
public void setUp() throws CannotGetJdbcConnectionException, DatabaseUnitException, SQLException, IOException {
	Session s = sessionFactory.openSession();
	TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s));

}

 

 在tearDown()方法中关闭session

public void tearDown() throws Exception {
	SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
	Session s = holder.getSession(); 
	s.flush();
	TransactionSynchronizationManager.unbindResource(sessionFactory);
}

完整的测试基类如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/beans.xml")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class  })
public class testUserModel  {
	
@Inject
private DataSource dataSource;
	
@Inject
private IUserDao userDao;
	
private IDatabaseConnection conn;
	
@Inject
private SessionFactory sessionFactory;
	

@Before
public void setUp() throws CannotGetJdbcConnectionException, DatabaseUnitException, SQLException, IOException {
Session s = sessionFactory.openSession();
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s));
conn = new DatabaseConnection(DataSourceUtils.getConnection(dataSource));
FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
IDataSet dataSet =  builder.build(new ClassPathResource("/user.xml").getInputStream());
DatabaseOperation.CLEAN_INSERT.execute(conn, dataSet);
	

@After
public void tearDown() throws Exception { SessionHolder holder = (SessionHolder)  TransactionSynchronizationManager.getResource(sessionFactory);
Session s = holder.getSession(); 
s.flush();
TransactionSynchronizationManager.unbindResource(sessionFactory); } 
}

 

你可能感兴趣的:(spring,JUnit,dbunit)