您好我已經測試此代碼使用JUnit 4:如何測試org.hibernate.Session?
public class UserDaoTest {
/**
* Runs before all test methods
*/
@BeforeClass
public static void createDB() {
sessionFactory = HibernateUtil.getSessionFactory();
userDao = new UserDaoImpl();
languageDao = new LanguageDaoImpl();
requestDao = new RequestDaoImpl();
feedbackDao = new FeedbackDaoImpl();
hostelDao = new HostelDaoImpl();
imageDao = new ImageDaoImpl();
}
/**
* Runs after all test methods
*/
@AfterClass
public static void closeSessionFactory() {
HibernateUtil.shutdown();
}
/**
* Runs before each test method
*
* @return
*/
@Before
public void beginTransaction() {
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
}
/**
* Runs after each test method
*/
@After
public void rollbackTransaction() {
if (transaction != null && transaction.isActive()) {
System.out.println("Rolling back trasnaction after @Test method");
// rollback transaction so that tests don't modify database
transaction.rollback();
}
}
@Test
public void testSaveUser() {
User user1 = new User("Ostap", "Stashyshyn", Gender.MALE);
// save user. It delegates to `session.save(user1)` method.
userDao.create(user1);
Integer userId = user1.getUserId();
Assert.assertNotNull(userId);
// causes persistent entities to be saved into persistent context
session.flush();
// read languages from db
List<User> users = userDao.readAll();
Assert.assertThat(users.size(), CoreMatchers.is(1));
// next method annotated with @After is running.
// It rollbacks transaction causing hibernate not to store data into database. Thus database state is the same as when entering this test method
}
它成功地測試,但是當我session.flush()
後設置斷點,去命令行我看到有用戶沒有行分貝。
調用userDao.readAll();
會導致hibernate發出select語句並返回用戶?
我在控制檯上看到插入和選擇語句,但沒有在數據庫中。但是當我撥打transaction.commit()
而不是session.flush()
時,那麼適當的數據將以db爲單位。
以上代碼正確的方式來測試保存用戶嗎?或者我應該撥打transaction.commit()
而不是session.flush()
?
編輯:我會堅持這種測試方式org.hibernate.Session
?
謝謝!
謝謝比爾。我將使用'session.flush()'!我認爲,爲了測試目的,數據應該放入數據庫中,但是你說只是將持久化實體與持久化上下文同步就足夠了。它是否正確? –
我已經更新了代碼。 –
在測試過程中數據是以db爲單位的。但是,通常交易將在測試完成後回滾 –