2010-04-04 34 views

回答

1

我使用片斷下面列出的,我沒有遇到任何問題

import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.hibernate.cfg.AnnotationConfiguration; 
import org.junit.*; 

import static org.junit.Assert.assertFalse; 
import static org.junit.Assert.assertTrue; 

public class ComponentsTest { 
    private static SessionFactory sf; 
    private static Session s; 
    private static Transaction tx; 

    @BeforeClass 
    public static void setUp() { 
     sf = new AnnotationConfiguration().configure().buildSessionFactory(); 
    } 

    @AfterClass 
    public static void tearDown() { 
     sf.close(); 
    } 

    @Before 
    public void open() { 
     s = sf.openSession(); 
     tx = s.beginTransaction(); 
    } 

    @After 
    public void close() { 
     tx.commit(); 
     s.close(); 
    } 
    @Test 
    public void testSth(){ 
     // 
    } 
1

假設你的事務管理器設置正確,下面的代碼將讓您的會議開:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:/META-INF/spring/applicationContext*.xml") 
public class SpringTest { 

    @Autowired private MyObjectDao myObjectDao; 

    @Test 
    @Transactional 
    public void test() throws IOException { 
     MyObject object = myObjectDao.find(objectId); 
     object.setProperty("propertyValue"); 
     MyObject savedObject = myObjectDao.save(object); 
     assertEquals(object.getProperty(), savedObject.getProperty()); 
    } 
}